Bob Davies
Bob Davies

Reputation: 2282

Removing a value from an array stored in Mongo document

I have a document in a Mongo collection which looks something like this:

{
  _id: [uuid]
  prop: 
    some: "text",
    subprop: ['foo', 'bar']
}

I'd like to avoid having to pull the whole record out, modify it and push it back if that's possible. What update can I run to have 'bar' removed from doc.prop.subprop, not knowing the index it's stored at?

Thanks :)

Upvotes: 0

Views: 114

Answers (1)

Louisa
Louisa

Reputation: 871

You should be able to do this using the $pull operator, which can pull a specific value from a field. You can use dot notation to get the subprop field:

db.foo.update( { _id : [uuid] }, { $pull : { "prop.subprop" : "bar" } } );

If you want to run the update for multiple documents in the collection, you'll need to set multi : true in your query with the following syntax:

db.foo.update( { _id : [uuid] }, { $pull : { "prop.subprop" : "bar" } }, { multi : true } ); 

This means that the update query will run on all documents that match { _id : [uuid] } in your collection.

Upvotes: 2

Related Questions