mongodb - 我可以在 MongoDB 聚合框架 $sort 上使用 2 个以上的字段吗?

标签 mongodb sorting aggregation-framework

使用以下 PyMongo 查询。我使用了 Mongo 网络研讨会中的一些技巧,他们建议使用 _id 字段存储时间戳,以提高性能和内存使用率。

cursor = db.dados_meteo_reloaded.aggregate( [
{
    "$match": {
        "_id": {
        "$gte": "0001:20120901",
        "$lte": "0001:20140215"
    },
        "TMP": {
            "$lt": 7.2
    }
    }
    },
    {
"$project": {
    "year": {
        "$substr": [
            "$_id",
            5,
            4
        ]
    },
    "month": {
        "$substr": [
            "$_id",
            9,
            2
        ]
    },

            "day": {
        "$substr": [
            "$_id",
           11,
            2
        ]
    }
}
},
  {
 "$group": {
    "_id": {"year":"$year","month":"$month","day":"$day"},
    "frio": {
        "$sum": 0.25
    }
}
},
    {"$sort":{"_id.year":1, "_id.month":1, "_id.day":1}}
])

我得到的结果只按天排序。当 时,在管道的 $sort 步骤中,我只使用

{"$sort":{"_id.year":1, "_id.month":1}

结果按年份和月份正确排序。 $sort 步骤中可以使用多少个字段有一些限制吗?

这里是一些示例文档

{
"_id" : "0001:20121201000000",
"RNF" : 0,
"WET" : 8,
"HMD" : 100,
"TMP" : 4.4
},
{
"_id" : "0001:20121201001500",
"RNF" : 0,
"WET" : 7.9,
"HMD" : 100,
"TMP" : 4.2
}

最佳答案

引用文档:

The $sort stage has the following prototype form:

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

所以对于 $sort 上可以使用多少字段没有限制阶段。


不过有内存restrictions :

The $sort stage has a limit of 100 megabytes of RAM. By default, if the stage exceeds this limit, $sort will produce an error. To allow for the handling of large datasets, set the allowDiskUse option to true to enable $sort operations to write to temporary files.

Pymongo使用 allowDiskUse 的语法选项是:

collection.aggregate(
    [
        { '$sort': { <field1>: <sort order>, <field2>: <sort order> ... } }
    ],    
    allowDiskUse = True
)

关于mongodb - 我可以在 MongoDB 聚合框架 $sort 上使用 2 个以上的字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29285804/

相关文章:

java - 在方法中调用方法?在这种情况下它是如何工作的? ( java )

json - MongoDB - 带有 group_by 的嵌套数组的总和

c# - MongoDB C# 驱动程序 - POCO 引用的序列化?

java - MongoDB 的 JMX 注册错误

algorithm - 直接选择排序中的比较次数

javascript - 如何比较数组并计算匹配项

node.js - 如何聚合数组中 ObjectID 出现的次数?

python-eve tokenauth 401错误

mongodb - 如何在 Mongoose 数组中的每个值前面添加一个字符串?

MySQL 从每个类别中选择前 N 个最便宜的产品