简体   繁体   中英

MongoDB - Most Recent Item for Each ID in List

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?

  • $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);

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM