Gebruik een aggregatieraamwerk waarbij uw pijplijnfasen $sort
, $group
en $project
uitdrukkingen:
Message.aggregate(
[
// Matching pipeline, similar to find
{
"$match": {
"to": req.user.username
}
},
// Sorting pipeline
{
"$sort": {
"created": -1
}
},
// Grouping pipeline
{
"$group": {
"_id": "$from",
"message": {
"$first": "$message"
},
"created": {
"$first": "$created"
}
}
},
// Project pipeline, similar to select
{
"$project": {
"_id": 0,
"from": "$_id",
"message": 1,
"created": 1
}
}
],
function(err, messages) {
// Result is an array of documents
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.json(messages)
}
}
);
If req.user.username ="admin"
, met uw monsterverzameling dan is het resultaat:
{
"result" : [
{
"message" : "message4",
"created" : "2015-04-01T11:59:21.005Z",
"from" : "user2"
},
{
"message" : "message5",
"created" : "2015-04-01T11:59:29.971Z",
"from" : "user1"
}
],
"ok" : 1
}