【问题标题】:Update nested array field inside another array in a mongo db document更新 mongodb 文档中另一个数组内的嵌套数组字段
【发布时间】:2018-12-08 02:55:03
【问题描述】:

我只是想知道如何更新 mongo db 文档中的嵌套数组字段。

这是我的架构的样子:

const userSchema = new Schema({
  email: {type: String, unique: true, lowercase: true},
  password: String,
  firstName: String,
  lastName : String,
  role: String,
  children: Array
});

这是文档的样子:

{
"_id" : ObjectId("5b3570f3150a0b57a4e7421e"),
"children" : [ 
    {
        "fullName" : "John doe",
        "yearGroup" : "4",
        "absences" : [],
        "id" : "765"
    }
],
"email" : "jdoe@gmail.com",
"firstName" : "John",
"lastName" : "Doe",
"role" : "parent",
"__v" : 1

}

我想将一个新对象推入“缺席”数组的位置。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    为此,您必须通过 update 操作使用 mongodb $push 运算符,我想这就是您想要做的,但您没有指定匹配查询。推送到absences 这样做(我假设匹配查询是children.fullName

    db.ops.update( { "children.fullName": "John doe" } , { $push: { "children.$.absences": "data to push" } } );
    

    $ 占位符告诉 mongodb 用匹配的数组索引替换它自己(即$)。

    如果您想防止 absences 字段中的重复元素,您必须使用 $addToSet 运算符

    db.ops.update( { "children.fullName": "John doe" } , { $addToSet: { "children.$.absences": "data to push" } } );
    

    【讨论】:

    • 我得到一个错误''cannot use the part (children of children.id) to traverse the element'
    猜你喜欢
    • 2017-04-28
    • 2022-01-02
    • 2013-03-19
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多