我正在尝试运行以下代码,但出现此错误。
OperationFailure: The field 'planet' must be an accumulator object, full error: {'operationTime': Timestamp(1614568170, 1), 'ok': 0.0, 'errmsg': "The field 'planet' must be an accumulator object", 'code': 40234, 'codeName': 'Location40234', '$clusterTime': {'clusterTime': Timestamp(1614568170, 1), 'signature': {'hash': b'\xa4\xd9\xcd\xae\xd9\x91\x05G;{L\x8d8\xaf\xea\xca\x03\xe9\xd5\xc6', 'keyId': 6902062171803353090}}} SEARCH
当我删除这部分
"count":{"$first":"$count"},
"letter":{"$first":"$_id.planet"}
},
然后它工作得很好,但没有给我预期的结果。
这是我的尝试:
pipeline = [
{"$group":{
"_id":{"planet":"$system.planet.letter",
"numbers_of_planets":"$system.numbers_of_planets"},
"count":{"$sum":1}
}},
{"$sort":{"count":-1,"_id.planet":1}},
{"$group":{
"_id":"$_id.numbers_of_planets",
"planet":{
"count":{"$first":"$count"},
"letter":{"$first":"$_id.planet"}
},
"grouping_count":{"$sum":1},
"total":{"$sum":"$planet.count"}
}},
{"$sort": {"numbers_of_planets":-1}},
{"$limit":3}
]
show_table(exoplanets.aggregate(pipeline))
答案 0 :(得分:0)
"errmsg" : "The field 'planet' must be an accumulator object"
错误在以下小组赛阶段:
{"$group":{
"_id":"$_id.numbers_of_planets",
"planet":{
"count":{"$first":"$count"},
"letter":{"$first":"$_id.planet"}
},
"grouping_count":{"$sum":1},
"total":{"$sum":"$planet.count"}
}},
具体来说,在这个片段中:
"planet":{
"count":{"$first":"$count"},
"letter":{"$first":"$_id.planet"}
},
MongoDB 在字段 $first
之后需要一个 group accumulator 运算符(例如,$sum
、"planet"
等),您在其中提供:{{1} };因此错误。您需要通过添加额外的 "planet": { "count" ...
阶段来解决您的想法:
$addFields