Here is the query for that.
db.collection.aggregate([
{
$unwind: "$array"
},
{
$group: {
_id: { _id: "$_id", a: "$a" },
count: { $sum: 1 }
}
},
{
$sort: { _id: 1 }
},
{
$group: {
_id: "$_id._id",
array: { $push: { item: "$_id.array", repeated: "$count" }}
}
}
])