1

I have a collection in mongodb which has the following format:

{
   parentId: "12345akNu",
   createdAt: "2018-12-02",
   complete: false
}

I would like to find all most recent records for a set of parentId's which are not completed. I currently have this query to find all records, but I cannot figure out how to only get the latest records.

collection.find({ parentId: { $in: list_of_ids }, completed: false});

For a single records this is the case of using findOne with a sort on {createdAt: -1}, but I need to run this in one query for multiple records if possible.

Update

As this has been suggested to be closed I am updating and clarifying the query.

This is for a Meteor application which (on the client side) has a limited interface to the mongodb drivers, supporting only find and findOne. It would be ideal if this could be achieved with only those calls.

Hans
  • 2,800
  • 3
  • 28
  • 40
  • 1
    Try `collection.aggregate([ { parentId: { $in: list_of_ids }, completed: false}, {"$sort":{"createdAt":-1}}, {"$group":{ "_id":"$parentId", "first":{"$first":"$$ROOT"} }} ])` – s7vr Jan 13 '18 at 23:44
  • 2
    Possible duplicate of [Group Mongo documents by id and get the latest document by timestamp](https://stackoverflow.com/questions/36603622/group-mongo-documents-by-id-and-get-the-latest-document-by-timestamp) – s7vr Jan 13 '18 at 23:47
  • I updated with some more context in this being part of a Meteor application where the aggregate function is not available client side. – Hans Jan 14 '18 at 00:09

0 Answers0