按出现次数对数组排序 mongodb
Sort an array by occurances mongodb
是否可以按出现次数对数组进行排序?
例如,给定
{
"_id": {
"$oid": "60d20d342c7951852a21s53a"
},
"site": "www.xyz.ie",
"A": ["mary", "jamie", "john", "mary", "mary", "john"],
}
return
{
"_id": {
"$oid": "60d20d342c7951852a21s53a"
},
"site": "www.xyz.ie",
"A": ["mary", "jamie", "john", "mary", "mary", "john"],
"sorted_A" : ["mary","john","jamie"]
}
我能够完成大部分的工作,但我不知道如何将它们重新组合成一个数组。
我一直在使用聚合管道
- 从
$match
开始寻找我想要的站点
- 然后
$unwind
使用路径:"$A"
- 下一个
$sortByCount
在 "$A"
- ????我不知道如何将它们重新组合在一起。
这是管道:
[
{
'$match': {
'site': 'www.xyz.ie'
}
}, {
'$unwind': {
'path': '$A'
}
}, {
'$sortByCount': '$A'
}, {
????
}
]
$group
nu _id
and A
,先获取site
并统计总元素
$sort
按 count
降序排列
$group
只用_id
得到第一个site
,构造A
的数组
[
{ $match: { site: "www.xyz.ie" } },
{ $unwind: "$A" },
{
$group: {
_id: { _id: "$_id", A: "$A" },
site: { $first: "$site" },
count: { $sum: 1 }
}
},
{ $sort: { count: -1 } },
{
$group: {
_id: "$_id._id",
site: { $first: "$site" },
A: { $push: "$_id.A" }
}
}
]
是否可以按出现次数对数组进行排序?
例如,给定
{
"_id": {
"$oid": "60d20d342c7951852a21s53a"
},
"site": "www.xyz.ie",
"A": ["mary", "jamie", "john", "mary", "mary", "john"],
}
return
{
"_id": {
"$oid": "60d20d342c7951852a21s53a"
},
"site": "www.xyz.ie",
"A": ["mary", "jamie", "john", "mary", "mary", "john"],
"sorted_A" : ["mary","john","jamie"]
}
我能够完成大部分的工作,但我不知道如何将它们重新组合成一个数组。
我一直在使用聚合管道
- 从
$match
开始寻找我想要的站点 - 然后
$unwind
使用路径:"$A"
- 下一个
$sortByCount
在"$A"
- ????我不知道如何将它们重新组合在一起。
这是管道:
[
{
'$match': {
'site': 'www.xyz.ie'
}
}, {
'$unwind': {
'path': '$A'
}
}, {
'$sortByCount': '$A'
}, {
????
}
]
$group
nu_id
andA
,先获取site
并统计总元素$sort
按count
降序排列$group
只用_id
得到第一个site
,构造A
的数组
[
{ $match: { site: "www.xyz.ie" } },
{ $unwind: "$A" },
{
$group: {
_id: { _id: "$_id", A: "$A" },
site: { $first: "$site" },
count: { $sum: 1 }
}
},
{ $sort: { count: -1 } },
{
$group: {
_id: "$_id._id",
site: { $first: "$site" },
A: { $push: "$_id.A" }
}
}
]