Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 599
Dooderino Avatar asked Oct 20 '25 08:10

Dooderino


1 Answers

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]}}}
])
like image 101
Volodymyr Synytskyi Avatar answered Oct 22 '25 05:10

Volodymyr Synytskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!