You can try,
$match
pname
condition$sort
bypname
ascending order (optional)$group
byvname
and push root object in items and make array$project
to show required fields and get 4 objects using$slice
db.collection.aggregate([
{ $match: { pname: "xy" } },
{ $sort: { pname: 1 } },
{
$group: {
_id: "$vname",
items: { $push: "$$ROOT" }
}
},
{
$project: {
_id: 0,
vname: "$_id",
items: { $slice: ["$items", 4] }
}
}
])
If you want all objects in root then you can add below pipelines after above pipelines,
$unwind
deconstruct items array to object$replaceRoot
to replace items object in root
{ $unwind: "$items" },
{ $replaceRoot: { newRoot: "$items" } }
CLICK HERE to find out more related problems solutions.