[英]MongoDB. How to carry calculated fields through an aggregation pipeline?
我正在尝试从json格式的一些OSM数据中收集一些见解。 这是我在MongoDB / PyMongo中使用的文档的示例:
{"amenity": "post_office",
"name": "Dominion Road Postshop",
"created": {"uid": "10829",
"changeset": "607706",
"version": "5",
"user": "myfanwy",
"timestamp": "2007-11-24T12:41:04Z"},
"pos": [-36.8801299, 174.7495053],
"created_by": "Potlatch 0.5d",
"type": "node",
"id": "61076379"}
因此,每个文档都有一个用户和一个便利设施。 我想查找每个用户记录的每个便利设施的数量除以每个用户记录的所有便利设施的数量。
因此,为了帮助阐明这些代码段,我将使用这些代码段查找每个单独的计数:
查询1.查找每个用户记录多少种便利设施:
amenity_per_user = coll.aggregate([{"$match":{"amenity":{"$exists":True}}},
{"$group":{"_id":{"user":"$created.user", "amenities":"$amenity"}, "count":{"$sum":1}}},
{"$sort":{"count":-1}}])
查询2。查找每个用户记录了多少个便利设施:
results = coll.aggregate([{"$match":{"amenity":{"$exists":True}}},
{"$group":{"_id":"$created.user", "count":{"$sum":1}}},
{"$sort":{"count":-1}}])
两者的答案都是(每项最多5个结果):
Finding how many of each amenity each user records:
{u'_id': {u'amenities': u'parking', u'user': u'Rudy355'}, u'count': 1886}
{u'_id': {u'amenities': u'post_box', u'user': u'Rudy355'}, u'count': 547}
{u'_id': {u'amenities': u'telephone', u'user': u'Rudy355'}, u'count': 485}
{u'_id': {u'amenities': u'parking', u'user': u'myfanwy'}, u'count': 451}
{u'_id': {u'amenities': u'restaurant', u'user': u'Rudy355'}, u'count': 429}
Find how many amenities each user records:
{u'_id': u'Rudy355', u'count': 6321}
{u'_id': u'myfanwy', u'count': 951}
{u'_id': u'Robert Ancell', u'count': 599}
{u'_id': u'lcmortensen', u'count': 366}
{u'_id': u'Marks2000', u'count': 228}
现在我要做的是将每个用户的最高舒适度(即,Rudy355为停车舒适度输入1886个条目)除以他们的总录音量(查询2)。 -因此,最终结果是Rudy355在“停车”设施中录制了0.3张唱片。 -1886/6321 = 0.3。
这是我必须要做的:
coll.aggregate([{"$match":{"amenity":{"$exists":True}}},
{"$group":{"_id":"$created.user", "user_count":{"$sum":1}}},
{"$group":{"_id":{"user":"$created.user", "amenities":"$amenity"}, "amenity_count":{"$sum":1},
"ucount":{"$push":"$user_count"}}},
{"$unwind":"$ucount"},
{"$project":{"$divide":{"$ucount", "$amenity_count"}}},
{"$sort":{"count":-1}}])
任何帮助都是极好的!
顺便说一句,我真的不喜欢使用$ push为'user_count'保存值的想法。 有谁知道保存像这样的计算字段的更好方法。
您可以尝试以下汇总。 $push
保存每个amenity
及其count
以供以后用total
用户便利设施计数来计算record
。
[
{"$match":{"amenity":{"$exists":True}}},
{"$group":{"_id":{"user":"$created.user", "amenity":"$amenity"}, "count":{"$sum":1}}},
{"$group":{"_id":"$_id.user", "total":{"$sum":"$count"}, "amenities":{"$push":{amenity:"$_id.amenity","count":"$count"}}}},
{"$unwind":"$amenities"},
{"$project:{"_id":0,"user":"$_id", "amenity":"$amenities.amenity", record":{"$divide":{"$amenities.count", "$total"}}}},
{"$sort":{"record":-1}}
]
您应该具有以下输出。
{"user":"Rudy355", "amenity":"parking", "record":0.3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.