Is it possible to sort an array by occurrences?
For Example, given
JavaScript
x
8
1
{
2
"_id": {
3
"$oid": "60d20d342c7951852a21s53a"
4
},
5
"site": "www.xyz.ie",
6
"A": ["mary", "jamie", "john", "mary", "mary", "john"],
7
}
8
return
JavaScript
1
9
1
{
2
"_id": {
3
"$oid": "60d20d342c7951852a21s53a"
4
},
5
"site": "www.xyz.ie",
6
"A": ["mary", "jamie", "john", "mary", "mary", "john"],
7
"sorted_A" : ["mary","john","jamie"]
8
}
9
I am able to get it most of the way there but I cannot figure out how to join them all back together in an array.
I have been using an aggregation pipeline
- Starting with
$match
to find the site I want - Then
$unwind
on with path:"$A"
- Next
$sortByCount
on"$A"
- ???? I can’t figure out how to group it all back together.
Here is the pipeline:
JavaScript
1
16
16
1
[
2
{
3
'$match': {
4
'site': 'www.xyz.ie'
5
}
6
}, {
7
'$unwind': {
8
'path': '$A'
9
}
10
}, {
11
'$sortByCount': '$A'
12
}, {
13
????
14
}
15
]
16
Advertisement
Answer
$group
nu_id
andA
, get firstsite
and count total elements$sort
bycount
in descending order$group
by only_id
and get firstsite
, and construct array ofA
JavaScript
1
20
20
1
[
2
{ $match: { site: "www.xyz.ie" } },
3
{ $unwind: "$A" },
4
{
5
$group: {
6
_id: { _id: "$_id", A: "$A" },
7
site: { $first: "$site" },
8
count: { $sum: 1 }
9
}
10
},
11
{ $sort: { count: -1 } },
12
{
13
$group: {
14
_id: "$_id._id",
15
site: { $first: "$site" },
16
A: { $push: "$_id.A" }
17
}
18
}
19
]
20