简体   繁体   English

更新mongo db文档中另一个数组内的嵌套数组字段

[英]Update nested array field inside another array in a mongo db document

I'm just wondering how I can update a nested array field inside a mongo db document. 我只是想知道如何更新mongo db文档中的嵌套数组字段。

Here is how my schema looks like: 这是我的架构的样子:

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

This is how the document looks like: 这是文档的样子:

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

} }

Where I want to push a new object into to 'absences' array. 我想将一个新对象推送到“缺少”数组的位置。

to do this you have to use the mongodb $push operator via the update operation, which i guess that is what you want to do, but you did not specify your match query. 为此,您必须通过update操作使用mongodb $push运算符,我想这就是您要执行的操作,但是您没有指定匹配查询。 To push to absences do this ( i assume the match query is children.fullName ) 要推到absences做到这一点(我假设匹配查询是children.fullName

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

the $ placeholder tells mongodb to replace it self ( ie $ ) with the matched array index. $占位符告诉mongodb用匹配的数组索引替换自身(即$ )。

incase you want to prevent duplicate elements in absences field you have to use the $addToSet operator 柜面要防止重复元素absences现场,你必须使用$addToSet操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM