MongoDB - 从数组中提取多个对象 [英] MongoDB - Pull multiple objects from an array

查看:51
本文介绍了MongoDB - 从数组中提取多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从看起来像这样的数组中删除多个对象.

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 }

当我使用 $pull 使用此代码.

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

但是如果我想删除多个具有不同faculty_number 的对象怎么办?我尝试使用 $each 方法,就像在数组中添加多个对象一样,但效果不佳.

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.

推荐答案

使用 $in 运算符传递教师值列表以从嵌入数组中删除文档.更多这里

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

试试

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

这篇关于MongoDB - 从数组中提取多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆