Reputation: 3706
Ok, imagine a collection like this:
[
{
"_id" : ObjectId("5b5f76eb2bfe4a1e9c473bd2"),
"machine" : "NY-D800",
"level" : "Fatal",
},
{
"_id" : ObjectId("5b5f76eb2bfe4a1e9c473bd2"),
"machine" : "NY-D889",
"level" : "Fatal",
},
{
"_id" : ObjectId("5b5f76eb2bfe4a1e9c473bd2"),
"machine" : "NY-D889",
"level" : "Info",
},
{
"_id" : ObjectId("5b5f76eb2bfe4a1e9c473bd2"),
"machine" : "NY-D800",
"level" : "Fatal",
},
...
]
I want to find documents that have level
set to 'Fatal' but I don't want to return duplicates (duplicate machine
). So for example 'NY-D800' is listed twice with 'Fatal' so I would want it to be returned only once. Finally I would like to limit the values returned to 10 items.
Recapping:
level
= 'Fatal'machine
Is this possible with MongoDB, Mongoose?
I tried this:
Logs
.distinct({'level': 'Fatal'})
.limit(10)
.exec(function (err, response){
var result = {
status: 201,
message: response
};
if (err){
result.status = 500;
result.message = err;
} else if (!response){
result.status = 404;
result.message = err;
}
res.status(result.status).json(result.message);
});
Upvotes: 1
Views: 39
Reputation: 46461
You can first $match
with the level
"Fatal" and then apply $group
with machine
Logs.aggregate([
{ "$match": { "level": "Fatal" }},
{ "$group": {
"_id": "$machine",
"level": { "$first": "$level" },
}},
{ "$limit": 10 },
{ "$project": { "machine": "$_id", "level": 1, "_id": 0 }}
])
Upvotes: 1