python操作mongodb之二聚合查询

Posted similarface

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作mongodb之二聚合查询相关的知识,希望对你有一定的参考价值。

#聚合查询
from pymongo import MongoClient
db = MongoClient(‘mongodb://10.0.0.9:27017/‘).aggregation_example
#准备数据
result = db.things.insert_many([{"x": 1, "tags": ["dog", "cat"]},
                              {"x": 2, "tags": ["cat"]},
                             {"x": 2, "tags": ["mouse", "cat", "dog"]},
                               {"x": 3, "tags": []}])
result.inserted_ids
‘‘‘
{ "_id" : ObjectId("576aaa973e5269020848cc7c"), "x" : 1, "tags" : [ "dog", "cat" ] }
{ "_id" : ObjectId("576aaa973e5269020848cc7d"), "x" : 2, "tags" : [ "cat" ] }
{ "_id" : ObjectId("576aaa973e5269020848cc7e"), "x" : 2, "tags" : [ "mouse", "cat", "dog" ] }
{ "_id" : ObjectId("576aaa973e5269020848cc7f"), "x" : 3, "tags" : [ ] }
‘‘‘
from bson.son import SON
#$unwind 解开-后面的变量
pipeline = [
     {"$unwind": "$tags"},
     {"$group": {"_id": "$tags", "count": {"$sum": 1}}},
     {"$sort": SON([("count", -1), ("_id", -1)])}
 ]
list(db.things.aggregate(pipeline))
#使用聚合函数with command
db.command(‘aggregate‘, ‘things‘, pipeline=pipeline, explain=True)


"""Map/Reduce"""
from bson.code import Code
mapper = Code("""
              function () {
                this.tags.forEach(function(z) {
                  emit(z, 1);
                });
              }
              """)

reducer = Code("""
                function (key, values) {
                  var total = 0;
                  for (var i = 0; i < values.length; i++) {
                    total += values[i];
                  }
                  return total;
                }
                """)
result = db.things.map_reduce(mapper, reducer, "myresults")
for doc in result.find():
    print doc

  

以上是关于python操作mongodb之二聚合查询的主要内容,如果未能解决你的问题,请参考以下文章

python3操作MongoDB的crud以及聚合案例,代码可直接运行(python经典编程案例)

04 MongoDB各种查询操作 以及聚合操作总结

mongodb Aggregation聚合操作之$sort

04 MongoDB各种查询操作 以及聚合操作总结

详细教程一文参透MongoDB聚合查询

mongoDB查询进阶聚合管道 -- 阶段操作符