我有一个收藏与文件在以下格式:(下面显示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}
}
})
1条答案
按热度按时间5n0oy7gb1#
可能是这样的:
解释道:
1.过滤符合条件的文档。
1.仅筛选购买历史记录成功。
1.对结果进行分组以查看匹配文档与匹配purchaseHistory得计数.
Playground