Node.js 按mongo聚合中无序字符串数组的内容分组
我对MongoDB(mongoose)中的聚合框架有一个问题,这就是问题所在。我有下面的数据库方案。所以我想做的是统计只有通过Node.js 按mongo聚合中无序字符串数组的内容分组,node.js,mongodb,mongoose,grouping,Node.js,Mongodb,Mongoose,Grouping,我对MongoDB(mongoose)中的聚合框架有一个问题,这就是问题所在。我有下面的数据库方案。所以我想做的是统计只有通过手机访问的人数,或者只有通过卡访问,或者两者都有。没有任何命令 { '_id': ObjectId, 'user_access_type': ['Mobile' , 'Card'] } { '_id': ObjectId, 'user_access_type': ['Card' , 'Mobile'
手机
访问的人数,或者只有通过卡
访问,或者两者都有。没有任何命令
{
'_id': ObjectId,
'user_access_type': ['Mobile' , 'Card']
}
{
'_id': ObjectId,
'user_access_type': ['Card' , 'Mobile']
}
{
'_id': ObjectId,
'user_access_type': ['Mobile']
}
{
'_id': ObjectId,
'user_access_type': ['Card']
}
现在我正在使用它,但它只按用户访问类型数组的顺序分组
[ { "$group" : { "_id": {"User" : "$user_access_type"} , "count": {"$sum" : 1} }]
这是输出:
{
"_id": {
"User": [
"Card",
"Mobile"
]
},
"count": 1
},
{
"_id": {
"_id": "5f7dce2359aaf004985f98eb",
"User": [
"Mobile",
"Card"
]
},
"count": 1
},
{
"_id": {
"User": [
"Mobile"
]
},
"count": 1
},
{
"_id": {
"User": [
"Card"
]
},
"count": 1
},
vs我想要的:
{
"_id": {
"User": [
"Card",
"Mobile" // we can say both
]
},
"count": 2 // does not depend on order
},
{
"_id": {
"User": [
"Mobile"
]
},
"count": 1
},
{
"_id": {
"User": [
"Card"
]
},
"count": 1
},
您也可以使用$function
,使用其他选项
$function
可以允许添加javascript
代码,您可以使用sort()
对数组进行排序
第二种选择
如果user\u access\u type
数组始终具有唯一的元素,则可以在user\u access\u type
数组上使用$setUnion
运算符作为自联合,这将以相同的顺序重新排序数组
db.collection.aggregate([
{
$addFields: {
user_access_type: {
$setUnion: "$user_access_type"
}
}
},
{
$group: {
_id: "$user_access_type",
count: { $sum: 1 }
}
}
])
您也可以使用$function
使用其他选项
$function
可以允许添加javascript
代码,您可以使用sort()
对数组进行排序
第二种选择
如果user\u access\u type
数组始终具有唯一的元素,则可以在user\u access\u type
数组上使用$setUnion
运算符作为自联合,这将以相同的顺序重新排序数组
db.collection.aggregate([
{
$addFields: {
user_access_type: {
$setUnion: "$user_access_type"
}
}
},
{
$group: {
_id: "$user_access_type",
count: { $sum: 1 }
}
}
])