Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

mongodb - 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?

question from:https://stackoverflow.com/questions/65934428/query-with-in-operator-and-limit-on-amount-of-data-loaded

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...