Documents:
{ "group" : "G1", "cat" : "Cat1", "desc": "Some description 1"}
{ "group" : "G1", "cat" : "Cat2", "desc": "Some description 2"}
{ "group" : "G1", "cat" : "Cat1", "desc": "Some description 3"}
{ "group" : "G1", "cat" : "Cat3", "desc": "Some description 4"}
{ "group" : "G1", "cat" : "Cat2", "desc": "Some description 4"}
Can someone help me, using Mongoose, how to find the records that have unique group and cat?
From the Mongoose API for distinct, I understand the that I can use just one field. But can the Model.distinct be used to find documents based on two fields?
I can't give you a Mongoose specific example, and your question is a bit vague. The aggregation equivalent of "But can the Model.distinct be used to find documents based on two fields?" is:
db.test.aggregate( { $group: { _id: { group: "$group", cat: "$cat" } } } );
Which returns:
{
"result" : [
{
"_id" : {
"group" : "G1",
"cat" : "Cat3"
}
},
{
"_id" : {
"group" : "G1",
"cat" : "Cat2"
}
},
{
"_id" : {
"group" : "G1",
"cat" : "Cat1"
}
}
],
"ok" : 1
}
If you want to find group/cat combinations that only occur once, then you would use:
db.test.aggregate(
{ $group: {
_id: { group: "$group", cat: "$cat" },
c: { $sum: 1 },
doc_ids: { $addToSet: "$_id" }
} },
{ $match : { c: 1 } }
);
Which returns:
{
"result" : [
{
"_id" : {
"group" : "G1",
"cat" : "Cat3"
},
"c" : 1,
"doc_ids" : [
ObjectId("5112699b472ac038675618f1")
]
}
],
"ok" : 1
}
From http://mongoosejs.com/docs/api.html#model_Model.aggregate I learn that you can use the aggregation framework in Mongoose like:
YourModel.aggregate(
{ $group: { _id: { group: "$group", cat: "$cat" } } },
function(err, result) {
console.log(result)
}
)