开发者

How come this MongoDB update doesn't work?

db.posts.update({}, {"pop_score":999});

db.posts.find({},{"pop_score":1});
{ "_id" : ObjectId("4d8eadd6df83500f3b000004"), "pop_score" : 0 }
{ "_id" : ObjectId("4d8eb1e3df83500f3b000035"), "pop_score" : 1 }
{ "_id" : ObjectId("4d8eb238df83500f3b000039"), "pop_score" : 1 }
{ "_id" : ObjectId("4d91377bdf8350063d000000"), "pop_score" : 1 }
{ "_id" : ObjectId("4d913c19df8开发者_开发问答350063d000001"), "pop_score" : 2 }
{ "_id" : ObjectId("4d8eacabdf83500f3b000000"), "pop_score" : 1 }

I update the pop_score to 999, for all posts. But when I query for them, it didn't update.


It did work, but only updates the FIRST matching document by default. I suspect you have SOME document in there that is now 999.

What you need to do is to tell MongoDB to update every matching document, by setting the optional multi flag to true:

db.posts.update({}, {"pop_score":999}, false, true)

This will update every document rather than just the first it finds.

You may wish to review the docs on updating as well which have more info on these flags.


Beware that update() replaces the found element with the one passed as argument, you should use the $set atomic operator to update a field's value (and of course, Brendan is right about the first vs. multiple match):

db.posts.update({}, { $set: { pop_score: 999 } }, false, true)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜