gpt4 book ai didi

javascript - 在 Mongodb 中使用 $pull 移除一个深度嵌入的对象

转载 作者:IT老高 更新时间:2023-10-28 12:30:01 24 4
gpt4 key购买 nike

我正在尝试从嵌入的数组中删除 ($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",
}
]
}
]
}

在这个例子中,我试图摆脱“Bobby”。

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

db.test.find({"one.two.three_id" : 456});

但是,我不知道如何使用 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}}}}});

我读到您不能使用两个位置 $ 运算符,并且您必须知道第二个的索引位置。但是,我想避免使用要删除的嵌入式字典的索引。

引用:mongodb 上拉

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

最佳答案

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

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

在这种情况下,$ 似乎代表了 first 匹配的数组级别的索引,因此即使我们在多个嵌套级别进行匹配,它也可以工作。

关于javascript - 在 Mongodb 中使用 $pull 移除一个深度嵌入的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com