Limit results of each $In

Is there a way to limit the results of each “$in”? Either in a find query or an aggregate query.


If I use an $in query, the query has 5 IDs that it is filtering for. Each of the IDs has 1000 documents in the database, and I only want 5 per ID.

A result would look like:
Id1: 5 documents

Id5: 5 documents

I’m not necessarily looking to group them, the above example would return as an array of documents.

My approach would be to use $documents with one document per ID such as

{ $documents : [
   { _id : Id1 } ,
   { _id : Id2 } ,
   /* ... */
   { _id : Id5 }
] }

The I would $lookup the collection using _id of $documents as localField. The foreignField would be the field you use in your $in. I would put a $limit:5 in the pipeline of the $lookup.