Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 615
TIMEX Avatar asked Dec 13 '22 13:12

TIMEX


1 Answers

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.

like image 186
Brendan W. McAdams Avatar answered Jan 08 '23 12:01

Brendan W. McAdams