我需要为我的文档设置一个默认值,但是仅当该字段不存在时。我的问题是我正在使用数组运算符。
我的要求是这样的:
db.myCollection.updateMany({}, { $set: { 'foo.$[].bar.$[].test': 42 }})
myCollection
包含以下两个文档:
{
foo: [
{ bar: [{ a: 1 }, { a: 2, test: 18 }] },
{ bar: [{ a: 1, test: 20 }, { a: 2, test: 18 }] }
]
}
{
foo: [
{ bar: [{ a: 1, test: 40 }, { a: 2, test: 18 }] },
{ bar: [{ a: 1, test: 20 }, { a: 2, test: 18 }] }
]
}
但是,如果该属性test
存在,则我不想覆盖它。因此,在我的示例中,我只想设置一个子元素的默认值(在第一个文档中)。
如何更改我的要求?
您可以使用arrayFilters,
b
为bar
是存在t
为test
不存在db.myCollection.updateMany(
{},
{ $set: { 'foo.$[b].bar.$[t].test': 42 } },
{
arrayFilters: [
{ "b.bar": { $exists: true } },
{ "t.test": { $exists: false } }
]
}
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句