Abhishek Vijjapu
Abhishek Vijjapu

Reputation: 42

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"] ?

Upvotes: 0

Views: 91

Answers (2)

Atish
Atish

Reputation: 4417

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

Upvotes: 0

Sede
Sede

Reputation: 61225

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" ] } } }} 
)

Upvotes: 1

Related Questions