0

I want to update a document using a nested value from that same document. So if I have an document that looks like this:

{
  _id: ObjectId("60b002d490b01b63eee5d4b7"),
  title: 'foo',
  meta: {
    createdTime: ISODate("2011-07-06T17:53:41.439Z"),
    updatedTime: ISODate("2021-07-06T17:53:41.432Z")
  }
}

I want to run a database operation that will copy the meta.updatedTime to another field (that we can call newProperty) on the document so that the end result would be this:

{
  _id: ObjectId("60b002d490b01b63eee5d4b7"),
  title: 'foo',
  meta: {
    createdTime: ISODate("2011-07-06T17:53:41.439Z"),
    updatedTime: ISODate("2021-07-06T17:53:41.432Z")
  },
  newProperty: ISODate("2021-07-06T17:53:41.432Z")
}

I know that I can do a find to get the document and then a separate update, but I was hoping to be able to do it all in one operation. This way if I'm running this operation on 50,000 or 100,000 records, I get the sense that a simple db operation would be faster than looping through the records and performing an operation on each one using javascript. But that might be negligible? Any help is appreciated.

0

Try this:

db.collection.updateMany(
    {}, 
    [ 
       { $addField: { newProperty: "$meta.updatedTime" } } 
    ]
)
2
  • When I do this, the string is literally added to the new property. Instead of newProperty: ISODate("2021-07-06T17:53:41.432Z"), I see newProperty: "$meta.updatedTime"
    – Josh Reep
    Jul 8 at 20:12
  • @JoshReep if you are using MongoDB v4.2 or higher, the above update operation should work fine; see Updates with Aggregation Pipeline.
    – prasad_
    Jul 9 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.