【发布时间】:2021-06-11 19:11:18
【问题描述】:
我正在尝试使用 mongoDb 聚合数据以收集每个用户的数据。我有以下查询:
DB.collection.aggregate([
{ "$facet": {
"instructions": [
{ $match: { company: ref } },
{ $group: {
_id : '$user._id',
firstName: { $first: "$user.firstName"},
lastName: { $last: "$user.lastName"},
total: { $sum: 1 },
completed: { $sum: {
"$cond": [
{ "$eq": [ "$completed.value", true ] },
1, 0
]}
},
mostPopularProduct: {
$sortByCount: "$productType"
},
mostPopularType: {
$sortByCount: "$instructionType"
}
}},
]
}},
{ "$project": {
"perClient": { "instructions": "$instructions" }
}}
}}
])
我正在尝试从与$match 匹配的所有文档中的字符串字段中获取我的集合中的mostPopularProduct(和mostPopularInstruction)。基本上是所有文档中出现最多的产品。组内还有一些计算。
目前,我收到以下错误:"unknown group operator '$sortByCount'"。现在我知道这是因为它在组内被使用,它不能。但我不确定如何达到预期的效果。我尝试使用$sum,但没有达到我想要的效果。不知道是不是我用错了。
有人可以指点我正确的方向吗?
编辑
好的,所以我可能对我想要什么有点含糊。让我澄清一下。
我之前用过$sortByCount,是这样的:
"mostPopularProduct": [
{ $match: { company: ref } },
{ $sortByCount: "$productType"}
],
我得到的结果是:
"mostPopularProduct": [
{
"_id": "car",
"count": 14
}, {
"_id": "house",
"count": 2
}
]
现在,我想做完全相同的事情,但我希望它在我的组内,所以基本上我想得到以下结果:
"perClient": {
"instructions": [
{
"_id": "5fd3db7427e9bc610e4daeaa",
"firstName": "firstName",
"lastName": "lastName",
"total": 8,
"completed": 1,
// NOW HERE ARE THE FIELDS I WANT
"mostPopularProduct": [
{
"_id": "car",
"count": 3
}
]
}, // all other clients follow
]
}
这是我试图在 $group 中使用 $sortByCount 实现的所需结果。
【问题讨论】:
-
如何达到预期的结果 =>很难预测你想要的结果,如果你在你的问题中添加一些示例文档和预期的结果会很有帮助。
-
谢谢@turivishal,我加了一个例子
标签: javascript mongodb aggregation