Python PyMongo usage summary, pythonpymongo Summary
What is PyMongo?
PyMongo is a driver that enables python programs to use Mongodb databases and be compiled using python.
Install
Environment: Ubuntu 14.04 + python2.7 + MongoDB 2.4
Download the software package from the official website. Click the link to open the package. decompress the package and use python setup. py install for installation.
Or use pip to install pip-m install pymongo.
Basic usage
Create a connection
import pymongo client = pymongo.MongoClient('localhost', 27017)
Or
import pymongo client = MongoClient('mongodb://localhost:27017/')
Connect to database
Db = client. mydb # or db = client ['mydb']
Connection Aggregation
Clustering is equivalent to a table in a relational database.
Collection = db. my_collection # Or collection = db ['my _ collection']
View all cluster names in the database
db.collection_names()
Insert record
collection.insert({"key1":"value1","key2","value2"})
Delete record
Delete all
collection.remove()
Delete based on conditions
collection.remove({"key1":"value1"})
Update record
Copy codeThe Code is as follows:
Collection. update ({"key1": "value1" },{ "$ set": {"key2": "value2", "key3": "value3 "}})
Query records
Query a record: find_one () returns the first record without any parameters. If the record contains any parameters, the record is searched and returned based on the conditions.
collection.find_one() collection.find_one({"key1":"value1"})
Query multiple records: find () returns all records without parameters and returns results with parameters based on conditions
collection.find() collection.find({"key1":"value1"})
View multiple aggregated records
for item in collection.find(): print item
View the total number of clustered records
print collection.find().count()
Sort query results
Sort on a single column
Collection. find (). sort ("key1") # The default value is collection in ascending order. find (). sort ("key1", pymongo. ASCENDING) # collection in ASCENDING order. find (). sort ("key1", pymongo. DESCENDING) # DESCENDING order
Sort on multiple columns
Copy codeThe Code is as follows:
Collection. find (). sort ([("key1", pymongo. ASCENDING), ("key2", pymongo. DESCENDING)])
Instance 1:
#! /Usr/bin/env python # coding: UTF-8 # Author: -- <qingfengkuyu> # Purpose: Use of MongoDB # Created: # The 32-bit version can only store up to GB of data (NoSQLFan: The maximum file size is 2 GB, and the production environment recommends 64-bit) import py1_import datetimeimport random # create connection conn = pymongo. connection ('10. 11.1.70', 27017) # connect to the database db = conn. study # db = conn ['Study '] # print all clustering names and connect the clustered print u'all clustering:', db. collection_names () posts = db. post # posts = db ['post'] print posts # insert record new_post = {"AccountID": 22, "UserName": "libing", 'date': datetime. datetime. now ()} new_posts = [{"AccountID": 22, "UserName": "liuw", 'date': datetime. datetime. now ()}, {"AccountID": 23, "UserName": "urling", 'date': datetime. datetime. now ()}] # The insert time of each record is different from that of posts. insert (new_post) # posts. insert (new_posts) # insert multiple data records in batches # Delete record print u'delete specified record: \ n', posts. find_one ({"AccountID": 22, "UserName": "libing"}) posts. remove ({"AccountID": 22, "UserName": "libing"}) # modify the posts record in the aggregation. update ({"UserName": "urling"}, {"$ set": {'accountid': random. randint (20, 50)}) # query records. The total number of statistical records is: ', posts. count (), posts. find (). count () print u'query a single record: \ n', posts. find_one () print posts. find_one ({"UserName": "liuw"}) # query all records print U' query multiple records: '# for item in posts. find (): # query all records # for item in posts. find ({"UserName": "urling"}): # query the specified record # for item in posts. find (). sort ("UserName"): # the query results are sorted by UserName. The default value is ascending. # for item in posts. find (). sort ("UserName", pymongo. ASCENDING): # the query results are sorted by UserName. ASCENDING is in ASCENDING order, and DESCENDING is in DESCENDING order for item in posts. find (). sort ([("UserName", pymongo. ASCENDING), ('date', pymongo. DESCENDING)]): # the query results are sorted by multiple columns. print item # view the query statement performance # posts. create_index ([("UserName", pymongo. ASCENDING), ("date", pymongo. DESCENDING)]) # Add the index print posts. find (). sort ([("UserName", pymongo. ASCENDING), ('date', pymongo. DESCENDING)]). explain () ["cursor"] # print posts. find (). sort ([("UserName", pymongo. ASCENDING), ('date', pymongo. DESCENDING)]). explain () ["nscanned"] # number of records queried during statement execution
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.