Why is this MongoDB update not working?

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 am updating pop_score to 999, for all posts. But when I request them, it is not updated.

+4
source share
2 answers

It really worked, but by default only updates the FIRST corresponding document. I suspect that you have SOME document, which is now in 999.

What you need to do is tell MongoDB to update each relevant document by setting the multi flag to true:

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

This will update every document, not just the first one that it finds.

You might want to look at update documents that have more information about these flags.

+11
source

Remember that update () replaces the found element with the argument passed as the argument, you must use the $set atomic operator to update the field value (and, of course, Brendan is right about the first or several matches):

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

All Articles