chx
chx

Reputation: 11780

MongoDB pull based on partial array?

I can do a $pull for a simple document:

> db.users.find();
{ "_id" : 4, "sessions" : [ { "sid" : "foo1" }, { "sid" : "bar" } ] }

> db.users.update({}, {"$pull": {sessions: {"sid" : "bar"}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

But if I have more information on the session:

> db.users.insert({_id:5, sessions: [ { sid: "foo"}, {sid:"bar", ssid:"test"}]});
> db.users.find();
{ "_id" : 4, "sessions" : [ { "sid" : "foo1" } ] }
{ "_id" : 5, "sessions" : [ { "sid" : "foo" }, { "sid" : "bar", "ssid" : "test" } ] }

> db.users.update({}, {"$pull": {sessions: {"sid" : "bar"}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

then the $pull fails.

Upvotes: 0

Views: 197

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

Your $pull is correct, but you need to add the multi: true option for the update to apply to both docs:

db.users.update({}, {"$pull": {sessions: {"sid" : "bar"}}}, {multi: true});

Upvotes: 1

Related Questions