简体   繁体   English

mongoDb - 如何从嵌套数组中删除 object

[英]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 .这是 mongoDB 中的数据,集合名为ProductCategory I want to find the product with _id "6246e3049b16cf549256ed79" which is "Arduino Nano V3.0 ATMEGA 328P (with USB Cable)" .我想找到_id为“6246e3049b16cf549256ed79”的产品,即“Arduino Nano V3.0 ATMEGA 328P (with USB Cable)” How can I find it and also delete it.我怎样才能找到它并删除它。

In order to delete from a nested array, you can use pipeline update and $filter for this:为了从嵌套数组中删除,您可以为此使用管道更新和$filter

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 .这将过滤products数组以仅包含其 id 不是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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM