简体   繁体   中英

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.

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. To push to absences do this ( i assume the match query is 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.

incase you want to prevent duplicate elements in absences field you have to use the $addToSet operator

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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