Skip to content
Advertisement

Mongodb positional operator is not working

When I am trying to update just “title”, it is working fine, but if I am trying to update the nested object in the array, it is not working.

Data: Data

Working:

const restaurant = await Restaurant.update(
    {_id: '60e6828e4992a2979fa0ba3e'},
    {$set: {title: "Hello}},
  );

Not working:

const restaurant = await Restaurant.update(
    {_id: '60e6828e4992a2979fa0ba3e', 'grades.grade': 85},
    {$set: {'grades.$.grade': 0}},
  );

Advertisement

Answer

Demo – https://mongoplayground.net/p/caFBz-lx8dQ

Use $[]

The filtered positional operator $[] identifies the array elements that match the arrayFilters conditions for an update operation

db.collection.update(
 {},
 { $set: { "grades.$[elem].grade": 0 }},
 { arrayFilters: [ {"elem.grade": 85 } ]}
)
Advertisement