I'd like to add a new field to a collection, with the value of the new field set to the value of an existing field.
Specifically, I'd like to go from this:
# db.foo.findOne() { "_id" : ObjectId("4f25c828eb60261eab000000"), "created" : ISODate("2012-01-29T16:28:56.232Z"), "..." : ... }
to this:
# db.foo.findOne() { "_id" : ObjectId("4f25c828eb60261eab000000"), "created" : ISODate("2012-01-29T16:28:56.232Z"), "event_ts" : ISODate("2012-01-29T16:28:56.232Z"), #same as created "..." : ... }
(New documents in this collection won't all have this peculiar redundancy, but I want to do this for my existing documents)
To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .
Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.
function addEventTsField(){ db.foo.find().forEach(function(doc){ db.foo.update({_id:doc._id}, {$set:{"event_ts":doc.created}}); }); }
Run from console:
addEventTsField();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With