Python operation MongoDB Two aggregation query

Source: Internet
Author: User

#聚合查询from Pymongo Import mongoclientdb = mongoclient (' mongodb://10.0.0.9:27017/'). aggregation_example# Prepare Data result =                             Db.things.insert_many ([{"X": 1, "tags": ["Dog", "Cat"]}, {"X": 2, "tags": ["Cat"]}, {"X": 2, "tags": ["Mouse", "Cat", "Dog"]}, {"X": 3, "tags": []}]) result.i Nserted_ids ' {"_id": ObjectId ("576aaa973e5269020848cc7c"), "X": 1, "tags": ["Dog", "Cat"]} {"_id": ObjectId ("576a Aa973e5269020848cc7d ")," 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 Untie-The following variable pipeline = [{"$unwind": "$tags"}, {"$group": {"_id": "$tags", "Count": {"$sum": 1}}, {"$sor T ": 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.for                Each (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 operation MongoDB Two aggregation query

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.