Nicolas Kao
Nicolas Kao

Reputation: 333

Find 5 unique most recent documents in database

I'm trying to make an endpoint to list the most recent 5 entries without returning a repeated value for a user.

this is what I have so far:

    SpaceHistory
    .find({owner: req.params.owner})
    .sort({"createdDate": -1})
    .exec(function(err, spaceHistory){
        if(err){
            return res.send(new errors.ServerError(err))
        }
        if(!spaceHistory){
            return res.send(new errors.ResourceNotFoundError('Space History Not Found'))
        }

        res.send(spaceHistory)
    })
}

my data looks like this:

[{
        "_id": "5c42826eb8cba061e8d2eea4",
        "owner": "5c427d3acbf49d4b7cfe8114",
        "space": "5c427de8cbf49d4b7cfe8115",
        "__v": 0,
        "createdDate": "2019-01-19T01:50:38.664Z"
    },
    {
        "_id": "5c428265b8cba061e8d2eea3",
        "owner": "5c427d3acbf49d4b7cfe8114",
        "space": "5c427de8cbf49d4b7cfe8115",
        "__v": 0,
        "createdDate": "2019-01-19T01:50:29.159Z"
    },
    {
        "_id": "5c428215b8cba061e8d2eea2",
        "owner": "5c427d3acbf49d4b7cfe8114",
        "space": "5c427d3acbf49d4b7cfe8114",
        "__v": 0,
        "createdDate": "2019-01-19T01:49:09.875Z"
    }]

I want it to return a maximum of 5 documents where "space" is never repeated and its sorted by the most recent. How would you approach this?

Upvotes: 0

Views: 39

Answers (1)

Saikat Chakrabortty
Saikat Chakrabortty

Reputation: 2680

as you are trying to fetch uniques values for space ,

well, so as .limit and .distinct doesnot go together, you can try with aggregate:

SpaceHistory.aggregate(
    [   {$match:{owner: req.params.owner}}
        { "$group": { "_id": "$space" } },
        {"$sort":{createdDate:-1}},
        { "$limit": 5 }
    ],
    function(err,results) {
       // results skipped and limited in here
    }
);

Upvotes: 1

Related Questions