且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将新属性添加到 MongoDB 中的嵌套子文档数组

更新时间:2023-11-24 22:15:46

为此,您使用 $set 运算符在更新语句中,同时通过 位置$ 运算符:

To do this you use the $set operator in an update statement, whilst referencing the matched array element via the positional $ operator:

db.collection.update(
    {
        "_id": ObjectId("559f85351554febf038b5c70"),
        "tech.tech_name": "Volution"
    },
    {
        "$set": {
            "tech.$.verified": true
        }
    }
)

所以它的作用是:

  1. .update() 的查询"或第一个参数部分都通过字段引用找到唯一的文档(不是真正必需的),然后在嵌套数组 my 中找到一个字段它是自己匹配的字段/属性".最后一部分对下一阶段很重要.

  1. The "query" or first argument portion of the .update() both finds a unique document ( not really required ) by field reference and secondly finds a field in the nested array my it's own matching "field/property". This last part is important for the next stage.

此处作为第二个"参数的 .update() 方法的更新"部分包含修改内容"的定义.在此处使用 $set 运算符可确保仅以任何方式修改引用的字段.

The "update" portion of the .update() method here as the "second" argument contains the definition for "what gets modified". Using the $set operator here makes sure that only the referenced fields get modified in any way.

然后这里的位置"$ 运算符确保只有从查询部分引用的该数组元素的匹配索引"才是更新的元素.这使用了 "dot notation" 形式的

Then the "positional" $ operator here makes sure that only the "matched index" of that array element referenced from the query portion is the element that gets updated. This uses the "dot notation" form of

$set: { "tech.$.verified": true }

引用元素中正确"的索引字段并创建"一个不存在的新属性或覆盖"现有值.

That references the "correct" indexed field in the element and "creates" a new property where one does not already exist or otherwise "overwrites" an existing value.

这些是其工作原理的基础知识.主要内容是:

Those are the basics of how this works. The primary things to take away from here are:

  1. 匹配要更新的数组中元素的索引值,并通过点表示法"引用它.

  1. Match an indexed value of an element in an array you wish to update and reference it via "dot notation".

使用 $set 操作或其他适当的 更新运算符",而不是在更新"中提供原始"对象结构,否则会覆盖"现有对象.

Use the $set operation or other appropriate "update operator" for the field rather than providing a "raw" object structure in the "update" that would otherwise "overwrite" the existing object.