Reputation: 5567
I have a list of content IDs and I’m trying to fetch the most recent comment (if one exists) for each of the content IDs in the list -
My query looks as follows:
const query = [
{
$match: {
content_id: { $in: myContentIds },
},
},
{ $sort: { ‘comment_created’: -1 } },
]
const results = await collection.find(query).toArray();
My understanding is this will fetch all of the comments related to the contentIds in the myContentIds
array and sort them in descending order based on the date.
I could then limit my results using { $limit: 1}
but this would return the most recent comment on any of the content items, rather than the most recent comment for each content.
How can I modify my query to return the most recent comment for each of my content items?
Upvotes: 2
Views: 539
Reputation: 36144
$group
by content_id
and get first recent document$replaceRoot
to replace that recent document in root (this is optional, you can use document by object recentComment
)const query = [
{ $match: { content_id: { $in: myContentIds } } },
{ $sort: { comment_created: -1 } },
{
$group: {
_id: "$content_id",
recentComment: { $first: "$$ROOT" }
}
},
{ $replaceRoot: { newRoot: "$recentComment" } }
];
const results = await collection.aggregate(query);
Upvotes: 3