How to use for loop in mongodb

23,077

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.

Share:
23,077
Mohammed shebin
Author by

Mohammed shebin

A java developer who is working on a startup company. Have knowledge in Mongo database and Amazon AWS.

Updated on July 26, 2022

Comments

  • Mohammed shebin
    Mohammed shebin almost 2 years

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

  • Mohammed shebin
    Mohammed shebin over 11 years
    Thnks fr the respnse. But what this 'row in cursor' stands for.?
  • Sammaye
    Sammaye over 11 years
    @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.
  • Mohammed shebin
    Mohammed shebin over 11 years
    ok. will u pls send me the exact code ..? also what u mnt by row._id ..?
  • Sammaye
    Sammaye over 11 years
    @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.
  • Sammaye
    Sammaye over 11 years
    @Mohammedshebin You cna also use the next functions as displayed here: mongodb.org/display/DOCS/Queries+and+Cursors
  • Mohammed shebin
    Mohammed shebin over 11 years
    i know it. iam a bit confused here. anyway thank u.. lemme try it out.
  • Sammaye
    Sammaye over 11 years
    @Mohammedshebin the dot notation on the object is the way things are accessed in the language javascript that you have put here and the for was a very basic loop of just saying that for every row in the cursor do this.