简体   繁体   中英

MongoDB: Remove array elements from a document

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM