Mongo从数组内部的数组中拉出对象

时间:2018-08-02 18:16:11

标签: node.js mongodb mongoose

我的mongoDB集合中有此文档

{ 
"_id" : ObjectId("5b633025579fac22e74bf3be"), 
"FLAGS" : [
    {
        "toSent" : [
            {
                "_id" : ObjectId("5b633025579fac22e74bf3c2"), 
                "phone" : "+84404040404"
            }, 
            {
                "_id" : ObjectId("5b633025579fac22e74bf3c1"), 
                "phone" : "+212652253403"
            }, 
            {
                "_id" : ObjectId("5b633025579fac22e74bf3c0"), 
                "phone" : "+212123456788"
            }
        ], 
        "_id" : ObjectId("5b633025579fac22e74bf3bf"), 
        "action" : "group_p_a"
    }, 
    {
        "toSent" : [
            {
                "_id" : ObjectId("5b633031579fac22e74bf3c9"), 
                "phone" : "+212651077199"
            }, 
            {
                "_id" : ObjectId("5b633031579fac22e74bf3c8"), 
                "phone" : "+84404040404"
            }, 
            {
                "_id" : ObjectId("5b633031579fac22e74bf3c7"), 
                "phone" : "+212652253403"
            }, 
            {
                "_id" : ObjectId("5b633031579fac22e74bf3c6"), 
                "phone" : "+212123456788"
            }
        ], 
        "_id" : ObjectId("5b633031579fac22e74bf3c5"), 
        "action" : "group_p_a"
    }
], 
"time" : ISODate("2018-08-02T16:24:05.747+0000"), 
"action_user_phone" : "+212123456788", 
"idGroup" : "e534379a-1580-4568-b5ec-6eaf981538d2", 
"nomGroup" : "MOH FOR EVER", 
"__v" : NumberInt(0)

} 待办事项 例如,我需要删除此元素{“ _id”:ObjectId(“ 5b633025579fac22e74bf3c2”),“ phone”:“ +84404040404”}

我要做什么

GroupEvents.update({}, {$pull:{FLAGS:{$elemMatch:{toSent:{phone: "+84404040404"}  }}}},function(err,ret){
    if(err)
        console.log("error"+err);
    if(ret)
        console.log(ret);
});

如果不匹配,它将删除toSent事件中的所有内容。

请帮助

1 个答案:

答案 0 :(得分:1)

您需要在此处使用$ positional运算符而不是$elemMatch

GroupEvents.update(
  { "Flags.toSent.phone": "+84404040404" },
  { "$pull": { "FLAGS.$.toSent": { "phone": "+84404040404" }}},
)

如果要从FLAGS数组的每个元素中删除,则需要使用$[]所有位置运算符

GroupEvents.update(
  { "Flags.toSent.phone": "+84404040404" },
  { "$pull": { "FLAGS.$[].toSent": { "phone": "+84404040404" }}},
)