python操作mongodb之二彙總查詢

來源:互聯網
上載者:User

標籤:

#彙總查詢from pymongo import MongoClientdb = 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 commanddb.command(‘aggregate‘, ‘things‘, pipeline=pipeline, explain=True)"""Map/Reduce"""from bson.code import Codemapper = 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之二彙總查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.