Reference Pymongo
Copy the Code code as follows:
>>> Import Pymongo
Create Connection Connection
Copy the Code code as follows:
>>> Import Pymongo
>>> conn = Pymongo. Connection (' localhost ', 27017)
Or
Copy the Code code as follows:
>>> from Pymongo import Connection
>>> conn = Connection (' localhost ', 27017)
When creating connection, specify the host and port parameters
Copy the Code code as follows:
>>> Import Pymongo
>>> conn = Pymongo. Connection (host= ' 127.0.0.1 ', port=27017)
Connecting to a database
Copy the Code code as follows:
>>> DB = conn. Chatroom
Or
Copy CodeThe code is as follows:
>>> db = conn[' chatroom ']
Connection Aggregation
Copy the Code code as follows:
>>> account = db. Account
Or
Copy CodeThe code is as follows:
>>> account = db["Account"]
View all aggregation names
Copy the Code code as follows:
>>> Db.collection_names ()
view a single record of a cluster
Copy the Code code as follows:
>>> db. Account.find_one ()
>>> db. Account.find_one ({"UserName": "Keyword"})
To view a clustered field
Copy the 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 in a cluster
Copy the 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 the Code code as follows:
>>> db. Account.find (). Count ()
>>> db. Account.find ({"UserName": "Keyword"}). Count ()
Sorting Clustered Query Results
Copy the Code code as follows:
>>> db. Account.find (). Sort ("UserName")--The default is ascending
>>> db. Account.find (). Sort ("UserName", Pymongo. Ascending)--Ascending
>>> db. Account.find (). Sort ("UserName", Pymongo. Descending)--descending
Clustered query results multi-column sorting
Copy the Code code as follows:
>>> db. Account.find (). Sort ([("UserName", Pymongo. Ascending), ("Email", Pymongo. Descending)])
Add a record
Copy the Code code as follows:
>>> db. Account.insert ({"AccountID": +, "UserName": "Libing"})
Modify a record
Copy the Code code as follows:
>>> db. Account.update ({"UserName": "Libing"},{"$set": {"Email": "Libing@126.com", "Password": "123"}})
Deleting records
Copy the Code code as follows:
>>> db. Account.remove ()--Delete all
>>> db. Test.remove ({"UserName": "Keyword"})