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?
db.coll.aggregate([
//match query
{$group:{_id:"$content_id",items:{$push:"$$ROOT"}}},
{$addFields:{items:{$slice:["$items", 5]}}}])
])
$match to check the content id is in the given list$group on each content id, add entire document to items listslice the array with the required elementsI suggest you to add a sort stage before project to ensure consistency across multiple hits.