#聚合查询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