How to set a field for every item in an array

Sample document:

{
  _id: 376818,
  buildingName: "test building",
  fuelTypeList: [
      {
         _id: 376820,
        buildingId: 376818,
        type: "Natural Gas"
      },
      {
         _id: 376821,
        buildingId: 376818,
        type: "District Cooling"
      }

  ]
  
}

I want to add a new field “id” to every item in fuelTypeList. I am using MongoDB Compass (Version 1.39.4 (1.39.4) ) MONGOSH terminal to run the command.

This is my query

 db.building.updateOne(
    { _id: 376818 },
    { $set: { fuelTypeList.$[].id: 5 } }
  );

and I am getting error

Error: clone(t={}){const r=t.loc||{};return e({loc:new Position("line"in r?r.line:this.loc.line,"column"in r?r.column:...<omitted>...)} could not be cloned.

According to https://www.mongodb.com/docs/manual/reference/operator/update/positional-all/, $ should be supported. What is wrong here?

this is a syntax error. it means your code is not formatted correctly. most likely it is the usage of dot notation that is not enclosed in double quotes.

rather than

try

"fuelTypeList.$[].id"
1 Like

that works, thank you :heart_eyes:

Instead of hard coding id = 5 for every item, if I want every item’s id equals to _id does the terminal support

  db.building.updateOne(
    { _id: 376818 },
    { $set: { "fuelTypeList.$[].id": "fuelTypeList.$[]._id" } }
  );

It updated the value as string
Screenshot 2023-09-24 at 10.52.53

If you need to use a current value from the same document you will need to use the update with aggregation.

The $[]is however not available. You will need to use $map to accomplish the modification of the array.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.