I want to update/insert a date into an object inside an array. I feel like I did everything as I was suppose to based on what I could find online but what happens is, that while I dont want to replace any properties inside my object, just add a property with value, it does gets replaced I have a n array of objects.
{
'name': 'stationXYZ',
'cancelledTrains': [
{
'info': 'infoinfoinfo',
},
],
}
db.stations.updateOne({ name: 'stationXYZ' }, { $set: {cancelledTrains: {date: new Date("2022-02-14T15:49:00Z")} }})
that code inserts the date, however removes the info property. WHat am I doing wrong? Thanks!
CodePudding user response:
This is just how the update syntax works, you are telling Mongo to set the cancelledTrains
field to the the { date: value }
object.
You want to use the dot notation to access specific fields:
db.stations.updateOne({ name: 'stationXYZ' }, { $set: {"cancelledTrains.date": new Date("2022-02-14T15:49:00Z") }})