2

I'm new to Mongo and thus trying to implement a use-case wherein I need to build a query to remove data from an array from inside a collection of documents.

Here is one of my documents:

{
"id" : 2,
"owners" : ["aa", "bb"]
}

Now I need to build a query to find all document records based on the owners and if present, remove them from the owners array.

For example, I sent aa in the query, then I need to remove that from all the documents that contains that owner.

I found somewhere this logic:

$db.coll.update({cond to identify document},{$pull:{'owners':{'aa':<>}}})

But don't understand how does this remove the data. Thanks in advance!

1 Answer 1

6

The following query updates a collection by removing the matched owners from owners array. The update query contains three blocks,

db.coll.update(
        { },
        { $pull: { owners: "aa" } },
        { multi: true }
    )

first block {}: it specify the query to find the documents, as we are considering all documents, we kept it blank

second block { $pull: { owners: "aa" } }: This one is removing matching elements from owners array from all documents.

third block { multi: true }: this block specifies that, we are considering update for all matching document, { multi: false } will update only the first matched document

To learn more you can follow this link

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for replying. Can you please explain what exactly is happening here?
A better approach would be to use a query condition in your update method in which the update operation only updates the documents matched by the query and use an index, rather than do a full collection scan and checks for each document in the collection then do a $pull which could be potentially slow on large datasets. Your solution can be further improved by including the query as db.coll.update( { "owners": "aa" }, { "$pull": { "owners": "aa" } }, { "multi": true } )
@chridam yes, it is true
Thanks very much gypsyCoder and chridam.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.