Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

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)

like image 326
Purrell Avatar asked Feb 10 '12 08:02

Purrell


People also ask

How do I add a new field to an existing record in MongoDB?

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 .

Is it possible to update MongoDB field using value of another field?

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.


1 Answers

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

Run from console:

addEventTsField(); 
like image 78
driangle Avatar answered Oct 26 '22 07:10

driangle