Is it possible to sort an array by occurrences?
For Example, given
{ "_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"] }
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:
[ { '$match': { 'site': 'www.xyz.ie' } }, { '$unwind': { 'path': '$A' } }, { '$sortByCount': '$A' }, { ???? } ]
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
[ { $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" } } } ]