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.

2 Answers 2

0

If you get error Unrecognized pipeline stage name: '$addField' when using $addField, give the below statement a shot.

db.collection.updateMany(
    {},
    [
       { $set: { newProperty: "$meta.createdTime" } }
    ]
)

2
  • 1
    The correct syntax is $addFields ($addField produces a syntax error).
    – prasad_
    Commented Dec 26, 2023 at 5:38
  • And, $addFields is an alias for $set, in an update with pipeline operation.
    – prasad_
    Commented Jun 3 at 2:48
0

Try this:

db.collection.updateMany(
    {}, 
    [ 
       { $addFields: { newProperty: "$meta.updatedTime" } } 
    ]
)
3
  • 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
    Commented Jul 8, 2021 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_
    Commented Jul 9, 2021 at 11:18
  • 1
    In the above code $addField aggregation stage name (produces syntax error) should be $addFields.
    – prasad_
    Commented Dec 26, 2023 at 5:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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