Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Here im trying to push some values to mongodb this is my pseudo code

 while read LINE
    do          
     addRow $para1 $param1 #pass value to the mongo
    done < ${FILE}

    function addRow() {
    para1="$1";
    para2="$2";
        if [ ! -z "$para1" ]
        then
             echo $1 $2;
             mongo dbname <<EOF
                newstuff = [{ "name" : "${1}", "age" : "${2}" }]
                db.collectionname.insert(newstuff);
             EOF
        else
           echo “Failed”;
        fi

    }

Its working fine, but i think that's not a proper way to do that job, i can see connect was re establish every time, any expertise suggestions may helpful

#### Process

bye
#file1

connecting to: dbname
[
     ##proc 1
]
bye
#file 2

MongoDB shell version: 2.4.8
connecting to: dbname
[
        ##proc 2
]
bye

#file3
MongoDB shell version: 2.4.8
connecting to: dbname
[
        ##proc 3
]
bye
share|improve this question
    
@Ba yeah thanks –  Dhanan Nov 19 '13 at 17:50
    
Why not script it using a language like Perl, Ruby, NodeJS and call that from your script? As is, you're starting/stopping the console each time. You'd need to batch up all of the instructions and call into the console once if you want to use the same connection. –  WiredPrairie Nov 19 '13 at 17:53

1 Answer 1

up vote 1 down vote accepted

Assuming each LINE in the FILE contains two parameters, I would first build the JS object for all the contents, then add it to mongo with one call:

items=()
while read para1 para2; do
    items+=( "$(printf '{"name":"%s","age":"%s"}' "$para1" "$para2")" )
done < "$FILE"
js_list=$(IFS=,; echo "[${items[*]}]")

mongo dbname <<EOF
newstuff = $js_list
db.collectionname.insert(newstuff);
EOF
share|improve this answer
    
@glenn-jackson Thank you very much mate !!, this is what im waiting for. can you explain the $(IFS=,; echo "[${items[*]}]") part for further modifications. –  Dhanan Nov 19 '13 at 20:52
    
That joins the array elements with commas. The form "${array[*]}" (quotes mandatory) joins the array elements using the first characters of $IFS. –  glenn jackman Nov 19 '13 at 21:16
    
Thanks again (y) –  Dhanan Nov 20 '13 at 19:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.