4

I’ve been trying to update the data in my mongoDB. I want to update all products with a new productName field.

my data looks something like:

{
    "id": "12345",
    "products": [{
        "id": 0
        "productCode": "test",
        "status": "PENDING",
    },
    {
        "id": 1
        "productCode": "test",
        "status": "COMPLETE",
    }],
}

When I try the following. I get this error The positional operator did not find the match needed from the query.

db.customers.updateMany(
  { id: "12345" },
  { $set: {
    "products.$.productName": "Name here" } 
  }
)

If I do account.0.productName then it’s fine and updates. I’m not sure why $ is not working for me

db.customers.updateMany(
  { id: "12345" },
  { $set: {
    "products.0.productName": "Name here" } 
  }
)
Melody C
  • 55
  • 1
  • 7

1 Answers1

12

Positional operator is not working because you are not using the array into the find (first object)

If you try this query it will work as expected because you have the position finding by products.id.

Otherwise, if you don't have the position into array where update, yo can't use $ operator in this way. You need this query:

db.collection.update({
  "id": "12345",
  
},
{
  "$set": {
    "products.$[].newField": "test2"
  }
},
{
  "multi": true
})

Mongo playground example here

Using $[] you can reference the array and add the value into each object.

$[] docs here

It says:

The all positional operator $[] indicates that the update operator should modify all elements in the specified array field.

That's exactly we want :)

J.F.
  • 13,927
  • 9
  • 27
  • 65