最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use for loop in mongodb - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited May 5, 2016 at 9:45 kadamb 1,7283 gold badges33 silver badges64 bronze badges asked Oct 18, 2012 at 8:30 Mohammed shebinMohammed shebin 4793 gold badges11 silver badges24 bronze badges 1
  • You sure this is Java? Doesn't look like it. – Nick H Commented Oct 18, 2012 at 8:39
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论