当前位置:Gxlcms > mysql > pymongo教程(2)聚合操作

pymongo教程(2)聚合操作

时间:2021-07-01 10:21:17 帮助过:57人阅读

在MongoDB中常用的聚合操作有 aggregation、map/reduce和group 。 首先先添加一些测试数据: db.things.insert({"x": 1, "tags": ["dog", "cat"]})db.things.insert({"x": 2, "tags": ["cat"]})db.things.insert({"x": 2, "tags": ["mouse", "cat", "dog"]})

在MongoDB中常用的聚合操作有 aggregation、map/reduce和group 。

首先先添加一些测试数据:

  1. db.things.insert({"x": 1, "tags": ["dog", "cat"]})
  2. db.things.insert({"x": 2, "tags": ["cat"]})
  3. db.things.insert({"x": 2, "tags": ["mouse", "cat", "dog"]})
  4. db.things.insert({"x": 3, "tags": []})

aggregation

以下例子是统计 tags 字段内的各个值的出现的次数。

  1. from bson.son import SON
  2. db.things.aggregate([
  3. {"$unwind": "$tags"},
  4. {"$group": {"_id": "$tags", "count": {"$sum": 1}}},
  5. {"$sort": SON([("count", -1), ("_id", -1)])}
  6. ])
  7. {'ok': 1.0, 'result': [{'count': 3, '_id': 'cat'}, {'count': 2, '_id': 'dog'}, {'count': 1, '_id': 'mouse'}]}

注意:aggregate操作要求服务器程序为 2.1.0 以上的版本。PyMongo 驱动程序为 2.3 以上的版本。

Map/Reduce

上面的操作同样也可以使用 Map/Reduce 完成。

  1. from bson.code import Code
  2. mapper = Code("""
  3. function () {
  4. this.tags.forEach(function(z) {
  5. emit(z, 1);
  6. });
  7. }
  8. """)
  9. reducer = Code("""
  10. function (key, values) {
  11. var total = 0;
  12. for (var i = 0; i < values.length; i++) {
  13. total += values[i];
  14. }
  15. return total;
  16. }
  17. """)
  18. result = db.things.map_reduce(mapper, reducer, "myresults")
  19. for doc in result.find():
  20. print(doc)
  21. {u'_id': u'cat', u'value': 3.0}
  22. {u'_id': u'dog', u'value': 2.0}
  23. {u'_id': u'mouse', u'value': 1.0}

map和reduce都是一个javascript的函数; map_reduce 方法会将统计结果保存到一个临时的数据集合中。

Group

group 操作与SQL的 GROUP BY 相似,同时比 Map/Reduce 要简单。

  1. reducer = Code("""
  2. function(obj, prev){
  3. prev.count++;
  4. }
  5. """)
  6. results = db.things.group(key={"x":1}, condition={}, initial={"count": 0}, reduce=reducer)
  7. for doc in results:
  8. print(doc)
  9. {'x': 1.0, 'count': 1.0}
  10. {'x': 2.0, 'count': 2.0}
  11. {'x': 3.0, 'count': 1.0}

注意:在MongoDB的集群环境中不支持 group 操作,可以使用 aggregation 或者 map/reduce 代替。

完整的MongoDB聚合文档: http://docs.mongodb.org/manual/aggregation/

人气教程排行