-------------------python calls MongoDB-------------------1, Official document: http://api.mongodb.org/python/current/ Tutorial.html 2, Linux installation instructions: sudo pip install Pymongo 3, test python driver:
1 #Coding=utf-82 3 " "4 Test Python driver5 " "6 7 #referencing the corresponding package8 ImportPymongo9 Ten #Create a MONGO client object OneClient = Pymongo. Mongoclient ("127.0.0.1", 27017) A #get database objects in MongoDB -db =Client.test_database - #Create a collection in the database theCollection =Db.test_collectiontwo - - #Create a data message to be added to the database, in JSON format -Post_data = {"username":"Xiaohao","pwd":"123456",} + - #to add the data, INSERTED_ID returns the added ID number information . +post_data_id =Collection.insert_one (post_data). inserted_id A at #display the inserted data information - PrintCollection.find_one () - - #Print the civil claim for all collections in the current database - Printdb.collection_names () - in #print information about the data in the current collection - forIteminchcollection.find (): to PrintItem + - #prints the number of data in the current collection the PrintCollection.count () * $ #make a Find query and print the number of bars of the query to the dataPanax Notoginseng PrintCollection.find ({"username":"Xiaohao"}). Count ()
4, Aggregation Examples:mongodb polymerization exercises
1 #Coding=utf-82 3 " "4 Perform an aggregation aggregation exercise5 " "6 7 #Primer Package8 ImportPymongo9 TenClient = Pymongo. Mongoclient ("127.0.0.1", 27017) One Adb =Client.aggregation_database - -Collection =db.aggregation_collection the - Collection.insert_many ([ -{"username":"xiaohao01","pwd":"111"}, -{"username":"xiaohao02","pwd":"222"}, +{"username":"xiaohao03","pwd":"333"} - ]) + A at #For item in Collection.find (): - #Print Item - - #python does not contain the son syntax and requires the use of son - - fromBson.sonImportSON in -Pipeline = [ to{"$unwind":"$pwd"}, +{"$group":{"_id":"pwd","Count":{"$sum": 1}}}, -{"$sort": SON ([("Count",-1), ("_id",-1)])} the ] * $result =List (Collection.aggregate (pipeline))Panax Notoginseng - PrintResult
Python calls MongoDB