1. 程式人生 > 實用技巧 >Update MongoDB field using value of another field

Update MongoDB field using value of another field

參考資料:https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field/28460030

mongo 4.2

類似,update table set filed = other-filed where filter ....

db.collection.<update method>(
   {},
   [
     {"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
   ]
)

mongo3.4+

db.collection.aggregate(
   [
     { "$addFields": { 
      "name": { "$concat": [ "$firstName", " ", "$lastName" ] } 
     }},
     { "$out": "collection" }
   ]
)

mongo 3.2 and 3.0

var cursor = db.collection.aggregate([ 
   { "$project":  { 
    "name": { "$concat": [ "$firstName", " ", "$lastName" ] } 
   }}
])
var requests = [];
cursor.forEach(document => { 
  requests.push( { 
    'updateOne': {
      'filter': { '_id': document._id },
      'update': { '$set': { 'name': document.name } }
     }
   });
  if (requests.length === 500) {
    //Execute per 500 operations and re-init
    db.collection.bulkWrite(requests);
    requests = [];
   }
});
if(requests.length > 0) {
   db.collection.bulkWrite(requests);
}

mongo 2.6 and 3.0


var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;
cursor.snapshot().forEach(function(document) { 
  bulk.find({ '_id': document._id }).updateOne( {
    '$set': { 'name': document.name }
   });
  count++;
  if(count%500 === 0) {
    // Excecute per 500 operations and re-init
    bulk.execute();
    bulk = db.collection.initializeUnorderedBulkOp();
   }
})
// clean up queues
if(count > 0) {
  bulk.execute();
}

mongo 2.4

cursor["result"].forEach(function(document) {
  db.collection.update(
     { "_id": document._id }, 
     { "$set": { "name": document.name } }
   );
})