在我的应用程序中,我有一个MongoDB文档,它将使用$inc
操作更新,以增加/减少appliesTo
对象中的数量。下面是一个示例对象
{
name: "test-document",
appliesTo: {
profiles: {
Profile1: 3,
Profile2: 1
},
tags: {
Tag1: 7,
Tag2: 1
}
}
}
在运行以下命令之后
await db.items.updateOne({name: "test-document"}, {$inc: {'appliesTo.profiles.Profile2': -1})
我的文件将改为
{
name: "test-document",
appliesTo: {
profiles: {
Profile1: 3,
Profile2: 0
},
tags: {
Tag1: 7,
Tag2: 1
}
}
}
我正在努力编写一个查询,该查询将删除所有键,其中的值为0
。我目前唯一的解决方案是迭代每个键并使用$unset
命令更新它。但这不是原子操作
是否有更明智的方法在一个查询中处理它?
发布于 2022-05-16 05:35:36
在单个常规更新quey中无法同时执行两种操作,您可以尝试从使用聚合管道进行更新 4.2开始执行MongoDB,
$cond
检查是一个键字段的值大于1,然后执行$add
操作,否则由$$REMOVE
操作符删除它await db.items.updateOne(
{ name: "test-document" },
[{
$set: {
"appliesTo.profiles.Profile2": {
$cond: [
{ $gt: ["$appliesTo.profiles.Profile2", 1] },
{ $add: ["$appliesTo.profiles.Profile2", -1] }
"$$REMOVE"
]
}
}
}]
)
https://stackoverflow.com/questions/72259179
复制相似问题