Použijte agregační rámec, kde vaše fáze kanálu mají $match
, $sort
, $group
a $project
výrazy:
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)
}
}
);
Pokud req.user.username = "admin"
, s vaší sbírkou vzorků je výsledek:
{
"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
}