简体   繁体   中英

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("4d913c19df8350063d000001"), "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.

请注意,update() 找到的元素替换为作为参数传递的元素,您应该使用$set atomic运算符来更新字段的值(当然,Brendan对于第一个匹配和多个匹配是正确的):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM