简体   繁体   English

mongoDB-如何在多个文档中查找和排序多个字段并将它们存储在单个数组中?

[英]mongoDB - How to find and sort multiple fields in several documents and store them in a single array?

The header describes the problem well I think. 标题很好地描述了我认为的问题。 I have a collection named "results" with serveral documents: 我有一个包含服务器文档的名为“结果”的集合:

{
    "_id" : "item_e4a2086048057ac9",
    "home" : "FH>87218379012",
    "username:" : "Jon Doe",
    "Apps" : {
        "game" : {
            "InVals" : {
                "ET" : {
                    "et1" : 1,
                    "et2" : 88,
                    "et3" : 7,
                    "et4" : 0.68,
                    "et5" : 5253,
                    "et6" : "7233-AL",
                    "et7" : "23-PL",
                    "et8" : "791-GY"
                }
            },
            "OutVals" : {
                "ET" : 74.00
            }
        }
    },
    "PAT" : 74
}

Second document: 第二份文件:

{
    "_id" : "item_a90a2086048057ac9",
    "home" : "FH>87218379012",
    "username:" : "Jon Doe2",
    "Apps" : {
        "game" : {
            "InVals" : {
                "ET" : {
                    "et1" : 0,
                    "et2" : 9,
                    "et3" : 96,
                    "et4" : 3218,
                    "et5" : 6,
                    "et6" : "65-AL",
                    "et7" : "265-PL",
                    "et8" : "4-GY"
                }
            },
            "OutVals" : {
                "ET" : 4.00
            }
        }
    },
    "PAT" : 4
}

And so on... Now I need to query all "PAT"-fields in the specific documents, where the field "home" is equal to "FH>87218379012", than sort them in descending order and store them in a variable which is an array: 依此类推...现在,我需要查询特定文档中的所有“ PAT”字段,其中“ home”字段等于“ FH> 87218379012”,而不是按降序对其进行排序并将其存储在变量中是一个数组:

var resultsArray = [74, 4....,n];

It would also be ok if there is an solution, where I have to store each "PAT"-Value in a single variable, sort them and save them in an array later. 如果有解决方案,那也可以,我必须将每个“ PAT”-值存储在单个变量中,对其进行排序,然后将它们保存在数组中。 At the end I just need to have all "PAT" values of the documents which have "FH>87218379012" as "home" in descended order in an array. 最后,我只需要按降序排列数组中具有“ FH> 87218379012”作为“ home”的文档的所有“ PAT”值。

Is that possible or do I have to change something in my collection? 是否可以,或者我必须更改收藏夹中的某些内容?

You can use an aggregation to match your PAT value, sort by that field and add a $group stage to $push the values to an array : 您可以使用聚合来匹配您的PAT值,按该字段排序并添加$ group阶段以推入数组:

db.coll.aggregate([{
    $match: {
        home: "FH>87218379012"
    }
}, {
    $sort: { PAT: -1 }
}, {
    $group: {
        _id: null,
        result: {
            $push: "$PAT"
        }
    }
}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM