使用Mongodb中的$ pull删除深度嵌入的对象

cat*_*aki 5 javascript mongodb

我正在尝试$pull从嵌入的数组中删除()一个对象.(使用javascript/node.js驱动程序.)

以下是示例数据,其中一个,两个,三个是级别:

{
    one : "All",
    one : [
        {
        name: "People",
        two: [
            { 
            three_id: 123,
            three: "Jonny",
            },
            { 
            three_id: 456,
            three: "Bobby",
            }
        ]
        },
        {
        name: "Animals",
        two: [
            { 
            three_id: 828,
            three: "Cat",
            },
            { 
            three_id: 282,
            three: "Dog",
            }
        ]
        }
    ]   
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我正试图摆脱"鲍比".

如果我愿意,我可以在"三级"成功匹配文档,如下所示:

db.test.find({"one.two.three_id" : 456});
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何消除该记录update.以下是一些尝试,其中没有一个工作:

// failed attempts
db.test.update({"one.two.three_id" : 456}, {$pull:{'one.$.two.$.three_id': 456}});
db.test.update({"one.two.three_id" : 456}, {$pull:{'three_id': 456}});

// deletes entire level two "People"
db.test.update({"one.two.three_id" : 456}, {$pull: {one: {two : {$elemMatch: {'three_id': 456}}}}});
Run Code Online (Sandbox Code Playgroud)

我读到你不能使用两个位置$ operators,你必须知道第二个的索引位置.但是,我想避免使用我想删除的嵌入式字典的索引.

参考:Mongodb拉

http://docs.mongodb.org/manual/reference/operator/update/pull/

Joh*_*yHK 5

$pull对象中键的值必须是您要定位的数组的路径。这似乎有效:

db.test.update(
    {'one.two.three_id': 456},
    {$pull: {'one.$.two': {three_id: 456}}}
);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它看起来像是$代表第一个匹配数组级别的索引,因此即使我们在多个嵌套级别进行匹配,它也能工作。