MongoDB: 从多个文档中的数组中删除文档

MongoDB: Delete documents from array in multiple documents

我还在了解 MongoDB 和 NoSql 数据库,我正在尝试更新 collection。

在我的 collection 中,我有多个文档如下所示:

{
    "name": "store1",
    "products": [
        {
            "name": "product 1",
            "reviews": [
                {
                    "user": "john doe",
                    "stars": 5,
                },
                {
                    "user": "jane doe",
                    "stars": 1,
                }
            ]
        },
        {
            "name": "product 2",
            "reviews": [
                {
                    "user": "jane doe",
                    "stars": 3,
                }
            ]
        }
    ]
}

每个文档都有一个文档数组“products”,该数组中的每个文档都有一个文档数组“reviews”

对于 collection 中的每个文档,我想从“产品”中删除至少有 1 星评论的文档 = "stars": 1

因此,对于上面的示例,更新后的文档将如下所示


{
    "name": "store1",
    "products": [
        {
            "name": "product 2",
            "reviews": [
                {
                    "user": "jane doe",
                    "stars": 3,
                }
            ]
        }
    ]
}

您可以使用 $pull 运算符删除数组中的对象。

db.collection.update({
  "products.reviews.stars": 1
},
{
  "$pull": {
    "products": {
      "reviews.stars": 1
    }
  }
})

示例here

查询 (聚合管道方式,需要 mongodb 4.2+)

  • 你在这里不需要聚合管道,但你也可以这样做

Test code here

db.collection.update({},
[
 ​{
   ​"$set": {
     ​"products": {
       ​"$filter": {
         ​"input": "$products",
         ​"cond": {
           ​"$not": [
             ​{
               ​"$in": [
                 ​1,
                 ​"$$p.reviews.stars"
               ​]
             ​}
           ​]
         ​},
         ​"as": "p"
       ​}
     ​}
   ​}
 ​}
])

因为你只有 1-5 星 filter is empty else "products.reviews.stars": 1, 可以使用。 (即使你对星星有索引,它的选择性也会很低,这可能会使事情变得更糟)