10

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..?.

1
  • You sure this is Java? Doesn't look like it. Commented Oct 18, 2012 at 8:39

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thnks fr the respnse. But what this 'row in cursor' stands for.?
@Mohammedshebin Each cursor is an object which when used like an array, in a foreach loop in most languages, will output a row which represents a row in your database. It is equal to using forEach on the rows. Infact you could replace the for for a forEach here.
ok. will u pls send me the exact code ..? also what u mnt by row._id ..?
@Mohammedshebin This is a simple loop, don't you know how to do loops? row._id is accessing the _id of that row you pull out. I have changed my code to work from the forEach function instead, it should work out the box.
@Mohammedshebin You cna also use the next functions as displayed here: mongodb.org/display/DOCS/Queries+and+Cursors
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.