opticon
opticon

Reputation: 3614

Get last created object for each user?

I have a collection, say, "Things":

{ id: 1
    creator: 1
    created: Today }
{ id: 2
    creator: 2
    created: Today }
{ id: 3
    creator: 2
    created: Yesterday }

I'd like to create a query that'll return each Thing created by a set of users, but only their most recently created thing.

What would this look like? I can get search my collection with an array of creators and it works just fine - how can I also only get the most recently created object per user?

Thing.find({ _creator : { "$in" : creatorArray })...

Upvotes: 0

Views: 156

Answers (1)

BatScream
BatScream

Reputation: 19700

You cannot find, sort and pick the most recent in just a single find() query. But you can do it using aggregation:

  • Match all the records where the creator is amongst the one who we are looking for.
  • Sort the records in descending order based on the created field.
  • Group the documents based on the creator.
  • Pick each creator's first document from the group, which will also be his latest.
  • Project the required fields.

snippet:

Thing.aggregate([
{$match:{"creator":{$in:[1,2]}}},
{$sort:{"created":-1}},
{$group:{"_id":"$creator","record":{$first:"$$ROOT"}}},
{$project:{"_id":0,
           "id":"$record.id",
           "creator":"$record.creator",
           "created":"$record.created"}}
], function(err,data){
   })

Upvotes: 3

Related Questions