Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use for loop in mongodb

I need to insert a new field(column) to mongodb collection which has now 5246 documents. The field should be auto incremented . So that i use an for loop . My query is as follows `

for(i=1;i<=5246;i++) {
    db.coll.update({},{$set:{"new_field":i}},false,true)
}; 

But my bad the output is as,

{new_field:5246},{new_field:5246},{new_field:5246},.......

Is there any problem with query..?.

like image 726
Mohammed shebin Avatar asked Oct 18 '12 08:10

Mohammed shebin


1 Answers

Why are you updating all records with no find criteria? Technically this loop is working as it should. What you need to do instead is loop through a cursor of your collection like so:

var cursor = db.coll.find(),
    i = 0;

cursor.forEach(function(x){
    db.coll.update({_id: x._id}, {$set:{new_field:i}})
    $i++;
});

Something like that would work instead.

like image 71
Sammaye Avatar answered Oct 17 '22 03:10

Sammaye