Referencing Pymongo
Copy Code code as follows:
Create Connection Connection
Copy Code code as follows:
>>> Import Pymongo
>>> conn = Pymongo. Connection (' localhost ', 27017)
Or
Copy Code code as follows:
>>> from Pymongo import Connection
>>> conn = Connection (' localhost ', 27017)
When creating connection, specify host and port parameters
Copy Code code as follows:
>>> Import Pymongo
>>> conn = Pymongo. Connection (host= ' 127.0.0.1 ', port=27017)
Connecting to a database
Copy Code code as follows:
Or
Copy Code code as follows:
>>> db = conn[' chatroom ']
Connection Aggregation
Copy Code code as follows:
>>> account = db. Account
Or
Copy Code code as follows:
>>> account = db[' account ']
View all clustered names
Copy Code code as follows:
>>> Db.collection_names ()
view a single record of a cluster
Copy Code code as follows:
>>> db. Account.find_one ()
>>> db. Account.find_one ({"UserName": "Keyword"})
To view a clustered field
Copy Code code as follows:
>>> db. Account.find_one ({},{"UserName": 1, "Email": 1})
{u ' UserName ': U ' libing ', U ' _id ': ObjectId (' 4ded95c3b7780a774a099b7c '), U ' Email ': U ' libing@35.cn '}
>>> db. Account.find_one ({},{"UserName": 1, "Email": 1, "_id": 0})
{u ' UserName ': U ' libing ', U ' Email ': U ' libing@35.cn '}
View multiple records of a cluster
Copy Code code as follows:
>>> for item in DB. Account.find ():
Item
>>> for item in DB. Account.find ({"UserName": "Libing"}):
item["UserName"]
to view aggregated record statistics
Copy Code code as follows:
>>> db. Account.find (). Count ()
>>> db. Account.find ({"UserName": "Keyword"}). Count ()
Clustered query Result Ordering
Copy Code code as follows:
>>> db. Account.find (). Sort ("UserName")--default to Ascending
>>> db. Account.find (). Sort ("UserName", Pymongo). Ascending)--Ascending
>>> db. Account.find (). Sort ("UserName", Pymongo). Descending)--descending
Clustered query results multiple-column sorting
Copy Code code as follows:
>>> db. Account.find (). Sort ([("UserName", Pymongo. Ascending), ("Email", Pymongo. Descending)])
Add a record
Copy Code code as follows:
>>> db. Account.insert ({"AccountId": "UserName": "Libing"})
Modify Records
Copy Code code as follows:
>>> db. Account.update ({"UserName": "Libing"},{"$set": {"Email": "Libing@126.com", "Password": "123"})
Delete a record
Copy Code code as follows:
>>> db. Account.remove ()--Delete all
>>> db. Test.remove ({"UserName": "Keyword"})