'mongoDb - How do I delete an object from a nested array

    "ProductCategory": [
        {
          "_id": "6246e0d09b16cf549256ed75",
          "name": "Arduino Boards",
          "desc": "this is for demo purpose",
          "date": "2022-03-31T18:30:00.000Z",
          "products": [
            {
              "name": "Arduino Uno R3 CH340G",
              "imgUrl": "",
              "price": "799",
              "desc": "",
              "_id": "6246e1fb9b16cf549256ed77"
            },
            {
              "name": "Arduino Nano V3.0 ATMEGA 328P (with USB Cable)",
              "imgUrl": "",
              "price": "599",
              "desc": "",
              "_id": "6246e3049b16cf549256ed79"
            }
          ]
        },
        {
          "_id": "6246e32d9b16cf549256ed7d",
          "name": "Sensors",
          "desc": "this is for demo purpose",
          "date": "2022-03-31T18:30:00.000Z",
          "products": [
            {
              "name": "PU6050 Gyroscope Sensor",
              "imgUrl": "",
              "price": "129",
              "desc": "",
              "_id": "6246e3d29b16cf549256ed7f"
            },
            {
              "name": "CCS811 Carbon Monoxide Gas Sensor",
              "imgUrl": "",
              "price": "1799",
              "desc": "",
              "_id": "6246e3d29b16cf549234ea3r"
            }
          ]
        }

This is a data in mongoDB with the collection named as ProductCategory. I want to find the product with _id "6246e3049b16cf549256ed79" which is "Arduino Nano V3.0 ATMEGA 328P (with USB Cable)". How can I find it and also delete it.



Solution 1:[1]

In order to delete from a nested array, you can use pipeline update and $filter for this:

db.ProductCategory.update({
  "products._id": idToDelete
},
[
  {
    $set: {
      products: {
        $filter: {
          input: "$products",
          as: "item",
          cond: {$ne: ["$$item._id", idToDelete]}
        }
      }
    }
  }
])

This will filter the products array to contain only items that their id is not idToDelete.

You can see it works on the playground

In order to just find the document, you can use:

db.ProductCategory.find({"products._id": idToDelete})

Solution 2:[2]

db.categories.deleteOne( {"_id": ObjectId("6246e3049b16cf549256ed79")});

https://www.mongodb.com/docs/manual/tutorial/remove-documents/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Blue