1

I have a huge mongodb collection and want to update one of the fields to the value of the id field.

The syntax I am trying is the following:

db.getCollection("products").updateMany(
{},     
{  $set: { ProductId: "$_id" }  },  
{})

This, however, sets the value to the string "$_id". If I leave away the quotes, I get an error message:

2021-02-18T15:55:53.170+0100 E QUERY [js] ReferenceError: $_id is not defined :

David Mason
  • 915
  • 1
  • 9
  • 27
  • Checkout [this answer](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) as well it has more information. – Umer Abbas Feb 18 '21 at 15:15

1 Answers1

2

Hi you can achieve this in MongoDB 4.2+, actually second parameter needs to be wrapped in an array. (just learned something new)

db.getCollection("products").updateMany(
    {},
    [
        {  $set: { ProductId: "$_id" }  }
    ]
)
Umer Abbas
  • 1,866
  • 3
  • 13
  • 19
  • 1
    That is called an update with aggregation pipeline. https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/ – D. SM Feb 18 '21 at 15:15
  • Thank you, I'm new to Mongo DB, now thinking about how many queries I can improve at work. very excited to implement these tomorrow. haha – Umer Abbas Feb 18 '21 at 15:19
  • I have MongoDB version 4.4, but if I try to execute this command I get an error message: E QUERY [js] Error: the update operation document must contain atomic operators :-( So this does not seem to be the solution so far. – David Mason Feb 18 '21 at 16:18
  • @DavidElsner Have you tried it in mongo shell ? – Umer Abbas Feb 18 '21 at 16:28
  • No I am using studio 3T... I will update it. Maybe that fixes it. – David Mason Feb 18 '21 at 17:51
  • 1
    It must be studio 3Ts problem. Like described here: https://stackoverflow.com/questions/58955143/mongodb-4-2-1-updatemany-error-the-update-operation-document-must-contain-at sorry... – David Mason Feb 18 '21 at 18:00
  • Yes, I saw that earlier that is why I asked if you used it in shell, I tried it in shell directly worked like a charm. – Umer Abbas Feb 18 '21 at 18:01