简体   繁体   中英

How to remove elements from array of an embedded document which are not in my array

This is my document.

{
    "group_name" : "Test Group 6 (Edit)",
    "created_on" : "1464367826787",
    "group_id" : "group_14",
    "members" : [
        {
            "user_id" : "user_7",
            "added_on" : "1464367826787"
        }
    ],
    "is_deleted" : 0
}

I'm having list of user_ids and I need to remove user_ids which are not in the list of user_ids I have. How to remove "user_50" if input list = ["user_7"] ?

You need to use the $nin operator to select your documents, the updateMany method if you want to update multiple documents or updateOne method to update a single document.

db.users.updateMany(
    {}, 
    { "$pull": { "members": { "user_id":  { "$nin": [ "user_7" ] } } }} 
)
db.users.update(
   {},
   {$pull:
   {members:{'user_id':{$ne:"user_7"}}}}, {multi:true})

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