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.
对于所有帖子,我将pop_score更新为999。但是当我查询它们时,它没有更新。
2 个解决方案
#1
11
It did work, but only updates the FIRST matching document by default. I suspect you have SOME document in there that is now 999.
它确实有效,但默认只更新FIRST匹配文档。我怀疑你有一些文件,现在是999。
What you need to do is to tell MongoDB to update every matching document, by setting the optional multi
flag to true:
您需要做的是通过将可选的multi标志设置为true来告诉MongoDB更新每个匹配的文档:
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.
您可能希望查看有关更新的文档,其中包含有关这些标志的更多信息。
#2
1
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):
请注意update()将找到的元素替换为作为参数传递的元素,您应该使用$ set atomic运算符来更新字段的值(当然,Brendan对于第一个匹配和多个匹配是正确的):
db.posts.update({}, { $set: { pop_score: 999 } }, false, true)
#1
11
It did work, but only updates the FIRST matching document by default. I suspect you have SOME document in there that is now 999.
它确实有效,但默认只更新FIRST匹配文档。我怀疑你有一些文件,现在是999。
What you need to do is to tell MongoDB to update every matching document, by setting the optional multi
flag to true:
您需要做的是通过将可选的multi标志设置为true来告诉MongoDB更新每个匹配的文档:
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.
您可能希望查看有关更新的文档,其中包含有关这些标志的更多信息。
#2
1
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):
请注意update()将找到的元素替换为作为参数传递的元素,您应该使用$ set atomic运算符来更新字段的值(当然,Brendan对于第一个匹配和多个匹配是正确的):
db.posts.update({}, { $set: { pop_score: 999 } }, false, true)