MongoDB - Pull multiple objects from an array

2020-05-27 23:36发布

问题:

Hi I'm trying to remove multiple objects from an array that looks like this.

{
"_id" : ObjectId("5a7da1bda21d5f3e8cf005b3"),
"owner" : "1",
"group_name" : "PAASCU Board",
"group_members" : [ 
    {
        "faculty_name" : "Cheska Dela Rosa",
        "faculty_number" : 2,
        "_id" : ObjectId("5a7da1bda21d5f3e8cf005b5")
    }, 
    {
        "faculty_name" : "Earl Sempio",
        "faculty_number" : 7323,
        "_id" : ObjectId("5a7da1bda21d5f3e8cf005b4")
    }, 
    {
        "faculty_number" : 203,
        "faculty_name" : "Sample",
        "_id" : ObjectId("5a7dbf7952bd150a94d83958")
    }, 
    {
        "faculty_number" : 8025,
        "faculty_name" : "Sample Postman",
        "_id" : ObjectId("5a7dc64a1cf5dd3d50167d53")
    }
],
"__v" : 0 }

It works when I remove a single object using the $pull with this code.

db.getCollection('groups').update({_id: ObjectId("5a7da1bda21d5f3e8cf005b3")}, {$pull: {"group_members": {"faculty_number":8025}}})

But what if I want to remove multiple objects with different faculty_number? I tried using the $each method just like how I add multiple objects in the array but it doesn't work well.

回答1:

Use $in operator to pass the list of faculty values to remove documents from embedded array. More here

Try

db.groups.update(
  {"_id": ObjectId("5a7da1bda21d5f3e8cf005b3")},
  {"$pull":{"group_members":{"faculty_number":{$in:[8025,7323]}}}}
)