Dooderino
Dooderino

Reputation: 91

mongo find limit each match

I have a mongo collection which looks something like this:

{
  title: String,
  category: String
}

I want to write a query that selects various categories, similar to this:

Collection.find({category: {$in: ['Books', 'Cars', 'People']});

But I want to only select a limited number of each category, for example 5 of each book, car, people. How do I write such a query? Can I do it one query or must I use multiple ones?

Upvotes: 4

Views: 1935

Answers (1)

Volodymyr Synytskyi
Volodymyr Synytskyi

Reputation: 4055

You can do it using mongodb aggregation. Take a look at this pipeline:

  1. Filter all documents by categories(using $match).
  2. Group data by categories and create array for items with the same category(using $group and $push).
  3. Get a subset of each array with a limited maximum length(using $project and $slice).

Try the following query:

db.collection.aggregate([
  {$match: {category: {$in: ['Books', 'Cars', 'People']}}}, 
  {$group: {_id: "$category", titles: {$push: "$title"}}}, 
  {$project: {titles: {$slice: ["$titles", 5]}}}
])

Upvotes: 4

Related Questions