Search code examples
mongodbreplacesub-array

Single update query to update a single document (containing subarray documents)?


I have an existing document in DB:

Plan Collection (In DB):

{ _id: ObjectId('XXX'),
  name: 'Plan A', 
  remark: 'YYY',
  products: [ {name: 'Pdt1', qty: '10'}, 
              {name: 'Pdt2', qty: '20'} ]
}

I need to do update to 'Plan A' doc with products entirely to below (no matching required to existing products in DB) below:

{ _id: ObjectId('XXX'),
  name: 'Plan A',
  remark: 'edited YYY',
  products: [ {name: 'Pdt1', qty: '10'},
              {name: 'Pdt3', qty: '30'},
              {name: 'Pdt4', qty: '40'}  ]

Question:

Is there a simple MongoDB way to update existing 'Plan A' document to update its fields + replace all products subarrays in DB? Thank you


Solution

  • If you want to replace the entire product subdocument you can do it with positional all $[] operator in MongoDb 3.6+

    var filter = {
        name: 'Plan A'
    };
    
    var update = {
        $set: {
            'products.$[]': [ 
                {name: 'Pdt1', qty: '10'},
                {name: 'Pdt3', qty: '30'},
                {name: 'Pdt4', qty: '40'}  
            ]
        }
    };
    
    var options = {
        multi: true
    };
    
    db.collection.update(filter, update, options);