mongodb - $pull 文档中的多个对象 - MongoDB
问题描述
"_id" : ObjectId("5e2f7ae123227916c02f1ce6"),
"items" : [ {
"_id" : ObjectId("5e2f89d63a983002e4562fb2"),
"item_id" : "123",
"upc" : "ean"
},
{
"_id" : ObjectId("5e2f89d63a983002e4562fb2"),
"item_id" : "456",
"upc" : "ean",
},
{
"_id" : ObjectId("5e2f89d63a983002e4562fb2"),
"item_id" : "242",
"upc" : "ean",
} ]
}
我想删除项目数组中的多个对象。我正在使用的查询是..
db.collection.update({}, {$pull: {items: {item_id: {$in: ["123", "456"] }} } } )
我检查了这个答案链接,这和我的一样。但这对我不起作用。
感谢你的帮助。
解决方案
您的查询应该没有任何问题,因为您使用了 .update(),它会从过滤器的结果中更新第一个找到的文档:{'items.item_id': {$in: ["123", "456"] }}
,因此可能刚刚更新了许多匹配该过滤器条件的文档 -您可能错过了观察,请打印该查询的输出。由于您在过滤器中没有提到任何内容{}
- 因此,如果您想更新与通过 update 传递的过滤器匹配的所有文档,请使用.updateMany()或{multi : true}
作为选项传递给 same .update()
。
例子 :
db.collection.update({}, {$pull: {items: {item_id: {$in: ["123", "456"] }}}}, {multi: true})
(或者)
db.collection.updateMany({}, {$pull: {items: {item_id: {$in: ["123", "456"] }}}})
推荐阅读
- rest - WebAPI中具有默认根参数的属性路由
- python - 无法修复未对齐的结果
- python - 从图像中检索表数据
- python - 在 Python 中,如何在列表中有一个反斜杠元素?
- python - 张量流卷积层中的 FLOPs
- snowflake-cloud-data-platform - 为什么 Snowflake 中的 FUTURE 授权默认需要 AccountAdmin?
- python - 整数很长时的Python整数除法
- java - 如何并行运行 @Before 注释?
- r - 有没有办法自定义 ggplot2 主题中的刻度?
- javascript - 使用 TamperMonkey 进行页面重新加载无限循环