如何在$ group聚合中返回第一个值和第二个值

时间:2020-03-31 07:20:16

标签: mongodb mongodb-query aggregation-framework

我有这段代码可以从组中获取第一个值:

db.slides.aggregate([
                    {"$match": {"deckid": {"$in": [ObjectId("5d6f9216a4d6980ecb8347a1")]}}},
                    { "$project": { "_id":1, "deckid":1, "slideid" :1, "messagecategories" : {
                        "$objectToArray": { "$mergeObjects":["$messagecategories", "$corrected.messagecategories"]}
                    }}},
                    { "$unwind": "$messagecategories"},
                    { "$sort": { "messagecategories.v": -1}},
                    { "$group":{"_id": "$_id", "messagecategories": { "$first": "$messagecategories" }}},
                    { "$sortByCount": "$messagecategories.k"}
                ])

示例o / p:

{
    "_id" : "Efficacy",
    "count" : 1
}

"messagecategories": { "$first": "$messagecategories" }将返回第一个值。 如何获得第一个值和第二个值?

请原谅我犯的任何错误,我是MongoDB查询的新手。

编辑

已删除

编辑2

样本文档:

{
    "_id" : ObjectId("5d75e92fa4d698248a997a51"),
    "deckid" : ObjectId("5d75e8eea4d698248a997a3d"),
    "page" : 2
    "messagecategories" : {
        "Guidelines" : "0.001016",
        "Trial Design" : "0.162572",
        "Safety" : "0.000373",
        "Efficacy" : "0.015276",
        "Cost" : "0.001291",
        "Indication" : "0.000489",
        "Summary" : "0.114031",
        "Other" : "0.0"
    },
    "corrected" : {
        "messagecategories" : {
            "Patient Profile" : 1.0
        },
        "id" : "5d75e92fa4d698248a997a51",
        "type" : "slide"
    }
}

基本上,我希望获得2个得分最高的消息类别。

上述文档的所需操作:

{
    "_id" : "Patient Profile",
    "count" : 1
}
{
    "_id" : "Trial Design",
    "count" : 1
}

1 个答案:

答案 0 :(得分:0)

非常感谢@Joe。

我能够做到这一点:

db.slides.aggregate([
                    {"$match": {"deckid": {"$in": [ObjectId("5d6f9216a4d6980ecb8347a1")]}}},
                    { "$project": { "_id":1, "deckid":1, "slideid" :1, "messagecategories" : {
                        "$objectToArray": { "$mergeObjects":["$messagecategories", "$corrected.messagecategories"]}
                    }}},
                    { "$unwind": "$messagecategories"},
                    { "$sort": { "messagecategories.v": -1}},
                    { "$group":{"_id": "$_id", "array1": { "$push": "$messagecategories" }}},
                    { "$project": { "messagecategories": { "$slice": [ "$array1", 2 ] } } }
                ])

o / p结构稍作更改,但我可以接受。