0

i'm trying to write an update query to update a column/filed of a collection. My collection has 4 fields: _id, name, date1, date2.

I'm trying to write an update query to set date1 = date2 and i tried using inner query as shown below but didn't work.

db.myCollection.updateMany(
    {},
    {
        '$set': 
                {
                 'date2':  db.myCollection.find({},{date1:1, _id:0}).limit(1)
                }
    }
);
James Z
  • 12,209
  • 10
  • 24
  • 44
Raj
  • 1,467
  • 3
  • 23
  • 51

2 Answers2

1

Maybe something like this( version 4.2+):

db.collection.update({},
[
{
  $addFields: {
     date1: "$date2"
  }
 }
],
{
 multi: true
})

playground

For your case ( Version 3.6 ):

 db.collection.find().forEach(
   function (elem) {
     db.collection.update(
         {
             _id: elem._id
          },
          {
            $set: {
                date1: elem.date2
            }
          }
       );
    }
  );
R2D2
  • 9,410
  • 2
  • 12
  • 28
  • Thanks @R2D2 for your response. I tried that but didn't work. I'm using mongo 3.6 – Raj Feb 18 '22 at 20:55
  • Aaa forgot to mention this is for 4.2+ , for earlier versions check old school answers here: https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field – R2D2 Feb 18 '22 at 20:57
  • added v 3.6 to my answer ... – R2D2 Feb 18 '22 at 21:05
1
var cursor = db.collection.find()

var requests = [];
cursor.forEach(document => { 
    requests.push( { 
        'updateOne': {
            'filter': { '_id': document._id },
            'update': { '$set': { 'date1': document.date2 } }
        }
    });
    if (requests.length === 500) {
        //Execute per 500 operations and re-init
        db.collection.bulkWrite(requests);
        requests = [];
    }
});

if(requests.length > 0) {
     db.collection.bulkWrite(requests);
}
Raj
  • 1,467
  • 3
  • 23
  • 51