mongodb 使用 OrderedDict 时“管道阶段规范对象必须包含一个字段”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23112221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"A pipeline stage specification object must contain exactly one field" when using OrderedDict
提问by bortzmeyer
I try to run an aggregate command:
我尝试运行聚合命令:
request = collections.OrderedDict([
("$unwind", "$tags" ),
("$group", { "_id" : "$tags" , "count" : { "$sum" : 1 } } ),
("$project", { "_id" : 0, "tag" : "$_id" , "count" : 1 } ),
("$sort", { "count" : -1 } ),
("$limit", 3 )])
print client.devoxx.talks.aggregate(request)
But MongoDB rejects it:
但是 MongoDB 拒绝了它:
pymongo.errors.OperationFailure: command SON([('aggregate', u'talks'), ('pipeline', [OrderedDict([('$unwind', '$tags'), ('$group', {'count': {'$sum': 1}, '_id': '$tags'}), ('$project', {'count': 1, '_id': 0, 'tag': '$_id'}), ('$sort', {'count': -1}), ('$limit', 3)])])]) failed: exception: A pipeline stage specification object must contain exactly one field.
It seems to me that I have each aggregate stage in one item of the ordered dict.
在我看来,我在有序字典的一项中拥有每个聚合阶段。
采纳答案by Neil Lunn
This is probaby very pymongo specific but it is also very unnecessary as the standard form of arguments for an aggregation pipeline is actually an array and may as well be simply specified like so, for example:
这可能是非常特定于 pymongo 的,但它也是非常不必要的,因为聚合管道的标准参数形式实际上是一个数组,也可以像这样简单地指定,例如:
request = [{ "$unwind": "$tags"}, { "$group": { "_id": "$tags" } }]
Which is always going to serialize in order and as such presents no problem.
哪个总是按顺序序列化,因此没有问题。
So there is no need to use an OrderedDict.
所以没有必要使用 OrderedDict。
You are perhaps confusing the behavior with recent changes to the mongo shell (from 2.6) that allows arguments to be specified without wrapping in an array. But JSON as with some other languages expects their "dictionary/hash" definitions to maintain their specified order.
您可能会将此行为与最近对 mongo shell(从 2.6 开始)的更改混淆,该更改允许指定参数而不用包装在数组中。但是 JSON 与其他一些语言一样,希望它们的“字典/哈希”定义保持它们指定的顺序。
So using an array/list syntax is stillthe preferred implementation.
所以使用数组/列表语法仍然是首选的实现方式。