Javascript MongoDb聚合在$group内使用$sortByCount
我正在尝试使用mongoDb聚合数据,以收集每个用户的数据。我有以下疑问:Javascript MongoDb聚合在$group内使用$sortByCount,javascript,mongodb,aggregation,Javascript,Mongodb,Aggregation,我正在尝试使用mongoDb聚合数据,以收集每个用户的数据。我有以下疑问: DB.collection.aggregate([ { "$facet": { "instructions": [ { $match: { company: ref } }, { $group: { _id : '$user._id',
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
)。基本上是所有文档中出现最多的产品。小组内部还进行了一些计算
当前,我收到以下错误:未知组运算符“$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实现的所需结果
下面是一个示例:示例文档:
[
{ userId: 1, productType: "car" },
{ userId: 1, productType: "car" },
{ userId: 1, productType: "bus" },
{ userId: 1, productType: "bus" },
{ userId: 2, productType: "bus" },
{ userId: 2, productType: "bus" }
]
根据$group
和userId
计算总数productType
仅通过$group
进行,并准备userId
和计数产品类型的数组
如何实现预期结果=>很难预测您的预期结果,如果您在问题中添加一些示例文档和预期结果,这将很有帮助。谢谢@turivishal,我添加了一个示例Wont,将新字段与以前或现有字段分开?我没有完全理解您的意思,只需发布您的实际文档。我添加了一个示例。您能确认这一点吗?谢谢@turivishal,看起来很完美。产品类型在集团内部,这让我很困惑。
db.collection.aggregate([
{
"$facet": {
"instructions": [
{
$group: {
_id: {
userId: "$userId",
productType: "$productType"
},
productTypeCount: { $sum: 1 }
}
},
{
$group: {
_id: "$_id.userId",
mostPopularProduct: {
$push: {
_id: "$_id.productType",
count: "$productTypeCount"
}
}
}
}
]
}
}
])