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.
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, 2022Comments
-
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 over 11 yearsThnks fr the respnse. But what this 'row in cursor' stands for.?
-
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 thefor
for aforEach
here. -
Mohammed shebin over 11 yearsok. will u pls send me the exact code ..? also what u mnt by row._id ..?
-
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 thatrow
you pull out. I have changed my code to work from theforEach
function instead, it should work out the box. -
Sammaye over 11 years@Mohammedshebin You cna also use the next functions as displayed here: mongodb.org/display/DOCS/Queries+and+Cursors
-
Mohammed shebin over 11 yearsi know it. iam a bit confused here. anyway thank u.. lemme try it out.
-
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 thefor
was a very basic loop of just saying that for everyrow
in thecursor
do this.