gpt4 book ai didi

mongodb - pullAll 同时删除嵌入的对象

转载 作者:可可西里 更新时间:2023-11-01 09:24:33 24 4
gpt4 key购买 nike

我有包含以下文档的数据库:

> db.bios.find({"name.first":"James"}).pretty()
{
"_id" : 9,
"name" : {
"first" : "James",
"last" : "Gosling"
},
"birth" : ISODate("1955-05-19T04:00:00Z"),
"contribs" : [
"Java",
"C",
"Scala",
"UNIX"
],
"awards" : [
{
"award" : "The Economist Innovation Award",
"year" : 2002,
"by" : "The Economist"
},
{
"award" : "Officer of the Order of Canada",
"year" : 2007,
"by" : "Canada"
},
{
"award" : "nobel",
"by" : "Stockholm"
},
{
"award" : "nobel2",
"by" : "Stockholm"
},
{
"award" : "oscar",
"year" : 2015,
"by" : "Hollywood"
}
]
}

我正在尝试编写查询以从 awards 数组中删除由“Stockholm”或“Hollywood”颁发的奖励对象,但以下查询不起作用:

> db.bios.update({"name.first":"James"}, {$pullAll:{"awards.by":["Stockholm","Hollywood"]}})
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "cannot use the part (awards of awards.by) to travers
e the element ({awards: [ { award: \"The Economist Innovation Award\", year: 200
2.0, by: \"The Economist\" }, { award: \"Officer of the Order of Canada\", year:
2007.0, by: \"Canada\" }, { award: \"nobel\", by: \"Stockholm\" }, { award: \"n
obel2\", by: \"Stockholm\" }, { award: \"oscar\", year: 2015.0, by: \"Hollywood\
" } ]})"
}
})
>

类似的查询适用于从 contribs 数组中删除项目:

> db.bios.update({"name.first":"James"}, {$pullAll:{"contribs":["Java","Fortran"
]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

所以这里的问题似乎与我正在处理嵌入对象这一事实有关。

非常感谢您的帮助。

谢谢!

最佳答案

$pullAll运算符实际上是一种“特殊情况”快捷方式,它适用于其中只有值的数组,例如您的替代情况。

你真正想要的是$pull它的参数是对数组中包含的文档的“查询”。所以你的列表然后成为 $in 的参数:

db.bios.update(
{ "name.first": "James" },
{
"$pull": {
"awards": { "by": { "$in": ["Stockholm", "Hollywood"] } }
}
}
)

因此,在您的另一个示例中,更长形式的 $pullAll 将是:

db.bios.update(
{ "name.first": "James" },
{
"$pull": { "contribs": { "$in": ["Java","UNIX"] } }
}
)

同样的事情,但只是“手写”形式。

关于mongodb - pullAll 同时删除嵌入的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102691/

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