0

I have the following collection:

{
   {
     field1: 11,
     field2: 22
   },
   {
     field1: 111,
     field2: 222
   },
   ...
}

And I want to add a new field3, which uses field1 and field2 to populate his properties, name and code.

Something like this:

  {
       {
         field1: 11,
         field2: 22,
         field3: {code: 11, name: 22}
       },
       {
         field1: 111,
         field2: 222,
         field3: {code: 111, name: 222}
       },
       ...
  }

I have tried:

db.<collection>.update(
       {
          $set:{field3: {code: '$field1', name:'$field2'}}
       },
       {
         multi:true
       } 
 )

But got the string values '$field1' and '$field2':

{
       {
         field1: 11,
         field2: 22,
         field3: {code: '$field1', name: '$field2'}
       },
       {
         field1: 111,
         field2: 222,
         field3: {code: '$field1', name: '$field2'}
       },
       ...
  }

I can try with aggregate and achieve the wanted result, but I think it can be done and with update.

Waiting for your suggestions, thanks.

Emerson Micu
  • 450
  • 8
  • 17
  • 2
    you can not use internal field as value of another field in regular update query, use [update with aggregation pipeline](https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/), just warp your update part in array like `[{ $set:{field3: {code: '$field1', name:'$field2'}} }]` see [playground](https://mongoplayground.net/p/SLyDNL_KEAG) – turivishal Jun 02 '21 at 18:41

1 Answers1

0

Starting in MongoDB 4.2, you can use the aggregation pipeline for update operations.

db.collection.update({},
[
  {
    $set: {
      field3: {
        code: "$field1",
        name: "$field2"
      }
    }
  }
],
{
  multi: true
})

Here is the working example: https://mongoplayground.net/p/sAQL9_Cjg0J

NeNaD
  • 18,172
  • 8
  • 47
  • 89
  • There are already quite a few answers that start with the sentence "Starting in MongoDB 4.2, you can use the aggregation pipeline for update operations". Should we start linking these together as duplicates? – Joe Jun 02 '21 at 20:09
  • It is from the MongoDB Docs: https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/. It does not answer the question, it just tells that aggregation pipeline can now be used to updated document as well. But the actual implementation depends on the question. So I would not link them as duplicates. – NeNaD Jun 02 '21 at 20:57
  • I've seen a lot of answers like this, that are essentially, "put [] around the update part to use aggregation operators". There must be a way we can consolidate. – Joe Jun 02 '21 at 21:18