mongoose MongoDB -如何删除对象数组中的元素?

sulc1iza  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(213)

我有一个项目,我使用mongodb作为数据库。所以我想以下
例如,有一个产品集合

products: [
  {
    "name": "Product 1",
    "products": [
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 13,
        "path": ""
      },
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 11,
        "path": ""
      },
     {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 10,
        "path": ""
     }
    ]
  },
  {
    "name": "Product 2",
    "products": [
     {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 10,
        "path": ""
     },
     {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 11,
        "path": ""
     }

    ]
  }
]

我想删除ID为:10从所有的文档集合产品中使用updatesmany或任何MongoDB查询所以在更新之后,最终的文档应该是这样的

products: [
  {
    "name": "Matériel crémation",
    "products": [
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 13,
        "path": ""
      },
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 11,
        "path": ""
      }
    ]
  },
  {
    "name": "Documents",
    "products": [
     {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 11,
        "path": ""
     }

    ]
  }
]
wlzqhblo

wlzqhblo1#

$filter$set连接起来

db.collection.update({},
[
  {
    $set: {
      products: {
        "$filter": {
          "input": "$products",
          "as": "p",
          "cond": {
            $ne: [
              "$$p.id",
              10
            ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

这里是Mongo Playground供您参考。

相关问题