[英]More than one connection opened in MongoDB using NodeJS and Mongoose
[英]Nodejs | Mongoose - Find docs based on more than one distinct fields
文件:
{ "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"}
有人可以使用猫鼬帮助我,如何查找具有唯一group
和cat
的记录?
从Mongoose API的distinct
,我了解到我只能使用一个字段。 但是可以将Model.distinct
用于基于两个字段查找文档吗?
我不能给您一个猫鼬的具体例子,您的问题有点含糊。 聚合等效项为“但是Model.distinct可以用于基于两个字段查找文档吗?” 是:
db.test.aggregate( { $group: { _id: { group: "$group", cat: "$cat" } } } );
哪个返回:
{
"result" : [
{
"_id" : {
"group" : "G1",
"cat" : "Cat3"
}
},
{
"_id" : {
"group" : "G1",
"cat" : "Cat2"
}
},
{
"_id" : {
"group" : "G1",
"cat" : "Cat1"
}
}
],
"ok" : 1
}
如果要查找仅出现一次的组/猫组合,则可以使用:
db.test.aggregate(
{ $group: {
_id: { group: "$group", cat: "$cat" },
c: { $sum: 1 },
doc_ids: { $addToSet: "$_id" }
} },
{ $match : { c: 1 } }
);
哪个返回:
{
"result" : [
{
"_id" : {
"group" : "G1",
"cat" : "Cat3"
},
"c" : 1,
"doc_ids" : [
ObjectId("5112699b472ac038675618f1")
]
}
],
"ok" : 1
}
从http://mongoosejs.com/docs/api.html#model_Model.aggregate中,我了解到您可以在Mongoose中使用聚合框架,例如:
YourModel.aggregate(
{ $group: { _id: { group: "$group", cat: "$cat" } } },
function(err, result) {
console.log(result)
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.