David Mason
David Mason

Reputation: 1449

Updating all fields of a mongodb collection with the value of the id field

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 :

Upvotes: 1

Views: 797

Answers (1)

Umer Abbas
Umer Abbas

Reputation: 1876

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" }  }
    ]
)

Upvotes: 2

Related Questions