Home > Net >  How to user inner query with mongoDB update operation?
How to user inner query with mongoDB update operation?

Time:02-19

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

Now, 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. Please suggest

db.myCollection.updateMany(
    {},
    {
        '$set': 
                {
                 'date2':  db.myCollection.find({},{date1:1, _id:0}).limit(1)
                }
    }
);

CodePudding user response:

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
            }
          }
       );
    }
  );

CodePudding user response:

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);
}
  • Related