简体   繁体   English

MongoDB - 从数组中提取多个对象

[英]MongoDB - Pull multiple objects from an array

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.当我使用带有此代码的$pull删除单个对象时,它会起作用。

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 ?但是如果我想删除多个具有不同faculty_number对象faculty_number办? I tried using the $each method just like how I add multiple objects in the array but it doesn't work well.我尝试使用$each方法,就像在数组中添加多个对象一样,但效果不佳。

Use $in operator to pass the list of faculty values to remove documents from embedded array.使用$in运算符传递教师值列表以从嵌入数组中删除文档。 More here更多here

Try试试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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