MongoDB limit group by results

You can try,

  • $match pname condition
  • $sort by pname ascending order (optional)
  • $group by vname 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] }
    }
  }
])

Playground


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" } }

Playground

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top