0

I have a collection of documents like this:

{
    text: "Hello",
    difficulty: 1
},
{
    text: "Forthwith I shall not be reluctant to hinder your endeavors.",
    difficulty: 509
}

I want to find the sentences that match a certain difficulty:

{
    difficulty: { $in: [7, 9, 45] }
}

So far so good. But I also want to limit the number of sentences I get for each difficulty.

For example, let's say my limit is 10 for the query above: I want to get up to 10 sentences with difficulty 7, up to 10 sentences with difficulty 9, and up to 10 sentences with difficulty 45 (up to 30 sentences total).

Is there a way to do this with a mongodb query, or will I have to retrieve all of the sentences and limit them programmatically?

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • 2
    I know the "title" of the marked duplicate may not appear to be about the same thing, but it actually is. In modern releases you could either use `$lookup` back onto the same collection as demonstrated there, or just live with separate parallel queries and limits. Most of the time I would personally implement as the latter, unless the former showed a significant performance improvement. Depends on the implementation. – Neil Lunn Nov 12 '18 at 03:56
  • @NeilLunn Thanks for clarifying, I was about to ask if you could elaborate on what I could use from the linked answer. – Peter Olson Nov 12 '18 at 03:59
  • The `$lookup` example. Should be right at the top of the content. Also a load of other rabble from the author about the other points there in longer form. – Neil Lunn Nov 12 '18 at 04:00

0 Answers0