1

I am working with applications using MongoDB, nodeJs. I have a document with 2 level nested data on it. I want to push data of a 2-level nested array based on a 1-level "uuid". I will attach my document picture and you will know exactly what I wanted.

enter image description here

Node code:

await collection.update(
{
 uuid: req.query.sub_uuid
},
{
 $push: { subtests.uuid: req.body }
});
await test.save();

Thanks in Advance.

1 Answer 1

1

You have to use $arrayFilters that you can put some constraint on your update element inside the array.

db.collections.updateMany({
  "subtests.uuid": 'your_uuid'
},
{
  $set: {
    { $push: { "subtests.$[el].subtrests": { /*item you want to push in the array */ } } }
  }
},
{
  arrayFilters: [
    {
      "el.uuid": 'your_uuid'
    }
  ]
})

with this approach, you can update only the element who have your uuid.

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

2 Comments

Thanks for your kind answer...But @Ashkan Actually I am using mongoose on my backend and I trying to execute this query but I am getting "CallBack.apply is not a function" error from my mongoose.....I search for array filtering in mongoose docs but I didn't found what I am looking for...Your understand my solution!.... You know how to do it in mongoose let me know....Thanks again.
I'm not an expert in mongoose, mostly use waterline in the projects. But the point is, whenever I want to do some complex queries like this one, use row query. Writing complex queries with ORMs is hard to write, read, and also hard to update. @RehanShah

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.