Add a new field to a collection with value of an existing field

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the creation of a field based on another field:

// {
//   "created" : ISODate("2012-01-29T16:28:56.232Z"),
//   "..." : "..."
// }
db.collection.updateMany({}, [{ $set: { event_ts: "$created" } }])
// {
//   "created" :  ISODate("2012-01-29T16:28:56.232Z"),
//   "event_ts" : ISODate("2012-01-29T16:28:56.232Z"),
//   "..." : "..."
// }
  • The first part {} is the match query, filtering which documents to update (here we keep all documents).

  • The second part [{ $set: { event_ts: "$created" } }] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias for $addFields, which allows including a new field to the document.


function addEventTsField(){
    db.foo.find().forEach(function(doc){
         db.foo.update({_id:doc._id}, {$set:{"event_ts":doc.created}});
    });
}

Run from console:

addEventTsField();

No, it is not possible. Only two steps thats you've probably know:

  1. Load document, read field. (you can load only specific fields: _id, and created in your case if performance is an issue)
  2. Atomic update of document (set event_ts by using loaded created field)

Tags:

Mongodb