2

i would like to update Elements that are nested inside of multiple Arrays, like:

{
  _id: 1,
  items:[{
    item_id: 1,
    desc:[{
      desc_id: 1,
      description: "Test entry"
    },
    {
      desc_id: 2,
      description: "Test entry 2"
    }]
  }]
}

How is it possible to edit "description" inside of the first desc element with Node and Mongoose. I tried:

Client.updateOne({"items.desc.desc_id": 1}, {$set:{"items.$.desc.$.description": "Other test entry"}})

1 Answer 1

1

If you want to update only the first desc item try:

Client.updateOne({
  "items.desc.desc_id": 1
},
{
  $set: {
    "items.$.desc.0.description": "Other test entry"
  }
})

See how it works on the playground example - by index

EDIT:

You were using the positional $ operator which update the first match. If you want to search the inner array by the desc_id use the $[<identifier>]:

db.collection.update(
  {"items.desc.desc_id": 1},
  {$set: {"items.$.desc.$[item].description": "Other test entry"}},
  {arrayFilters: [{"item.desc_id": 1}]}
)

See how it works on the playground example by desc_id

But you are still using the positional $ operator for the external array, meaning you will only update the first match inside it.

To update all items according the desc_id, use the all positional operator $[] for the external array:

db.collection.update(
  {"items.desc.desc_id": 1},
  {$set: {"items.$[].desc.$[item].description": "Other test entry"}},
  {arrayFilters: [{"item.desc_id": 1}]}
)

See how it works on the playground example all items by desc_id

Sign up to request clarification or add additional context in comments.

2 Comments

That isnt really what i am looking for. I dont really want to search them by the Array index, i want to search them by the desc_id.
Updated the answer accordingly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.