1

文件:

{ "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 for 中distinct,我了解到我只能使用一个字段。但是可以Model.distinct用于根据两个字段查找文档吗?

4

1 回答 1

6

我不能给你一个猫鼬的具体例子,你的问题有点含糊。“但是可以使用 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)
    }
) 
于 2013-02-06T14:48:25.670 回答