首页 > 解决方案 > $set 仅当字段不存在时在 Mongodb 中使用数组运算符时

问题描述

我需要为我的文档设置一个默认值,但前提是该字段不存在。我的问题是我正在使用数组运算符。

我的要求是这样的:

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存在,我不想覆盖它。所以在我的例子中,我只想设置一个子元素的默认值(在第一个文档中)。

我怎样才能改变我的要求呢?

标签: mongodb

解决方案


您可以使用arrayFilters

  • bbar存在创建一个变量
  • ttest不存在创建一个变量
db.myCollection.updateMany(
    {},
    { $set: { 'foo.$[b].bar.$[t].test': 42 } },
    {
        arrayFilters: [
            { "b.bar": { $exists: true } },
            { "t.test": { $exists: false } }
        ]
    }
)

推荐阅读