Home > Software engineering >  How to remove all occurrences of array element in nested array in mongodb
How to remove all occurrences of array element in nested array in mongodb

Time:11-16

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 !

CodePudding user response:

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.

  • Related