Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
Query with $In operator and limit on amount of data loaded

I’m running the following query

const query = { 
 $and: [
   { 
     $or: [ 
       {
         status: ‘PROCESSED’
       }, 

       {
         status: ‘IN_PROGRESS’
       }, 
     ],
   },  
   {
      content_id: { $in: contentIds }, 
   }, 
], 
};

in order to obtain all the data where the content_id is in a given list. I would like to obtain the 5 most recent data items for each content_id.

I know I can accomplish this by running an individual query for each content id, sorting by content_date DESC and setting a limit of 5 - I would like to achieve all of this in one query, rather than running individual ones for each content id, is this possible?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

db.coll.aggregate([
     //match query
     {$group:{_id:"$content_id",items:{$push:"$$ROOT"}}}, 
     {$addFields:{items:{$slice:["$items", 5]}}}])
])
  1. $match to check the content id is in the given list
  2. Then $group on each content id, add entire document to items list
  3. Then slice the array with the required elements

I suggest you to add a sort stage before project to ensure consistency across multiple hits.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!