Home > Enterprise >  MongoDB mongoose, insert value in array
MongoDB mongoose, insert value in array

Time:03-10

I have a collection "MyCollection" like this

_id: ObjectId('asdasdasd')
myArray: Array
  0: Object
     _id: ObjectId('asdadas')
     name: "My object A"
     description: "My description A"
  1: Object
     _id: ObjectId('bsdadas')
     name: "My object B"

name and description are present in the model.

How could I insert a "description" in the 1: Object?

I know how can overwrite the entire array, or how to add a property in an object, example:

await MyCollection.updateMany(
  {name: 'some filter, but in my example I only have 1 document'},
  {
    'someObject.someNewOptions.myNewOption': 'example of new value'
  }
);

But how do something like that in an array?

CodePudding user response:

db.collection.update({
  "myArray._id": "bsdadas"
},
{
  "$set": {
    "myArray.$.description": "My description B"
  }
})

mongoplayground

  • Related