totalHotelsInTown=hotels.aggregate([ {"$group": {"_id": "$Town", "TotalRestaurantInTown": {"$sum":1}} } ])
NumOfHotelsInTown={}
for item in totalHotelsInTown:
NumOfHotelsInTown[item['_id']]=item['TotalRestaurantInTown']
results = hotels.aggregate(
[{"$match": {"cuisine": cuisine}},
{"$group": {"_id": "$town", "HotelsCount": {"$sum": 1} }}, {"$project": {"HotelsCount":1,"Percent": {"$multiply": [{"$divide": ["$HotelsCount", NumOfHotelsInTown["$_id"]]}, 100]}}}, {"$sort": {"Percent": 1}},
{"$limit": 1}])
我想将"_id"
字段的值作为键传递给python字典,但是解释器将"$_id"
本身作为键而不是它的值,并因此给出一个KeyError
。任何帮助都将不胜感激。谢谢
“NumOfHotelsInTown”字典包含地点和酒店数量的键值对
当我试图从NumOfHotelsInTown字典中检索值时, 我使用“$\u id”动态地给出密钥
我得到的确切错误是:
{"$group": {"_id": "$borough", "HotelsCount": {"$sum": 1} }}, {"$project": {"HotelsCount":1,"Percent": {"$multiply": [{"$divide": ["$HotelsCount", NumOfHotlesInTown["$_id"]]}, 100]}}}, {"$sort": {"Percent": 1}},
KeyError: '$_id'
我知道您正在尝试做什么,但是您不能在MongbDB
aggregate
期间动态运行python代码你应该做的是:
例如:
相关问题 更多 >
编程相关推荐