使用以下 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 theallowDiskUse
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/