简体   繁体   English

从文档中的数组中拉出

[英]$pull from array in document

I am trying to $pull from an array within a mongodb document. 我试图从mongodb文档中的数组中拉出$。

The document has the structure: 该文件具有以下结构:

{
    "_id" : ObjectId("54ee62ef688b41ff072b934b"), 
    "pictures" : [ 
        {
            "url" : "...", 
            "_id" : ObjectId("54ee6303688b41ff072b934d") 
        }, 
        { 
            "url" : "...", 
            "_id" : ObjectId("54ee6304688b41ff072b934e")
        }, 
        { 
            "url" : "",
            "_id" : ObjectId("54ee6304688b41ff072b934f") 
        } 
    ]
}

I tried the update object 我尝试了更新对象

var update = { $pull: { pictures: {$elemMatch: {_id:req.params.picid } } } }

db.activity.update({_id: new ObjectId(req.params.id)}, update)

which returns writeresult: 1, but the picture is never removed. 它返回writersult:1,但是图片永远不会被删除。

ps I am using node, hense the req.params.picid ps我正在使用节点,围绕req.params.picid

The $pull operator acts as a query document in itself and is also considered against every element of the array so $elemMatch is not needed: $pull运算符本身就充当查询文档,并且也考虑到数组的每个元素,因此不需要$elemMatch

var update = { 
   "$pull": { "pictures": { "_id": new ObjectId(req.params.picid) } }
};

You also need to cast your "string" from request params to an ObjectId . 您还需要将请求参数的“字符串”转换为ObjectId

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

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