3

My DataBase Structure is as following , it has only one document and nested array of products which consists ref to product document's id.

{
_id:"6371e078393a5194cc674369"
data: Array
  [0]:{
    image:
    title:
    products: Array
      [0]:product1Id
      [1]:product2Id
      [2]:product3Id
  },
  [1]:{
    image:
    title:
    products: Array
      [0]:product2Id
      [1]:product3Id
      [2]:product4Id
  },
}

My requirement is when I remove product3 from the product document I want to delete its references too. So here i want to delete product3Id from the nested array.

Updated Document would look like:

{
_id:"6371e078393a5194cc674369"
data: Array
  [0]:{
    image:
    title:
    products: Array
      [0]:product1Id
      [1]:product2Id
  },
  [1]:{
    image:
    title:
    products: Array
      [0]:product2Id
      [1]:product4Id
  },
}

My tries:

result = await homeSpecialModel.updateMany(
  {
    _id: "6371e078393a5194cc674369",
  },
  // { $pull: { data: { products: { $eleMatch: new ObjectId(id) } } } } -- 1st try
  // { $pull: { "data.products": new ObjectId(id) } } -- 2nd try
);

Both didn't seem to work !

2
  • Is "_id" an ObjectId or a string? Commented Nov 16, 2022 at 4:45
  • 1
    It is the id of the main document, I have updated the question for more clarity Commented Nov 16, 2022 at 4:47

1 Answer 1

2

Here's one way to do it using "arrayFilters".

db.collection.update({
  _id: "6371e078393a5194cc674369"
},
{
  "$pull": {
    "data.$[elem].products": ObjectId("6371e078393a5194cc67436b")
  }
},
{
  "multi": true,
  "arrayFilters": [
    {
      "elem.products": ObjectId("6371e078393a5194cc67436b")
    }
  ]
})

Try it on mongoplayground.net.

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

1 Comment

can you help me to solve this stackoverflow.com/questions/74455783/…

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.