Nodejs | mongoose – 基于多个不同的字段查找文档
文件:
{ "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"}
有人可以帮助我,使用mongoose,如何find有独特的group
和cat
的logging?
从Mongoose API来看,我明白我只能使用一个字段。 但是, Model.distinct
可以用来查找基于两个字段的文档吗?
我不能给你一个mongoose的具体例子,你的问题有点含糊。 “但是可以使用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 }
如果你想find只出现一次的组/猫组合,那么你可以使用:
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) } )