mongodb 使用计数对数组对象进行Mongo聚合

yyhrrdl8  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(148)

我有一个收藏与文件在以下格式:(下面显示2个示例文档)
第一份文件:

{
  "date": 20221101,
  "time":1500,
  "productCode": "toycar",
  "purchaseHistory": [
    {
      "clientid": 123,
      "status": "SUCCESS"
    },
    {
      "clientid": 456,
      "status": "FAILURE"
    }
  ]
}

第二份文件:

{
  "date": 20221101,
  "time": 1500,
  "productCode": "toycar",
  "purchaseHistory": [
    {
      "clientid": 890,
      "status": "SUCCESS"
    },
    {
      "clientid": 678,
      "status": "SUCCESS"
    }
  ]
}

我想查询上述内容,并以下面的格式打印输出,其中purchaseHistory.status = 'SUCCESS',date = 20221101:

{productCode:"toycar", "time": 1500, "docCount": 2, "purchaseHistCount":3}

**我如何才能做到这一点?**我尝试了以下方法:

db.products.aggregate({
  $match : {date:20221101, 'purchaseHistory.status':'SUCCESS'},
  "$group": {
    "_id": {
      "pc": "$productCode",
      "time": "$time"
    },
    "docCount": {$sum :1}
  }
})
5n0oy7gb

5n0oy7gb1#

可能是这样的:

db.collection.aggregate([
{
 $match: {
  date: 20221101,
  "purchaseHistory.status": "SUCCESS"
}
},
{
"$addFields": {
  "purchaseHistory": {
    "$filter": {
      "input": "$purchaseHistory",
      "as": "ph",
      "cond": {
        $eq: [
          "$$ph.status",
          "SUCCESS"
        ]
      }
    }
   }
  }
 },
 {
   $group: {
       _id: {
          t: "$time",
         pc: "$productCode"
      },
       docCount: {
          $sum: 1
      },
       purchaseHistCount: {
        $sum: {
          $size: "$purchaseHistory"
       }
      }
     }
   }
  ])

解释道:
1.过滤符合条件的文档。
1.仅筛选购买历史记录成功。
1.对结果进行分组以查看匹配文档与匹配purchaseHistory得计数.
Playground

相关问题