The MongoDB hierarchy is database-->collection--and document
Installing MongoDB, starting the MONGO service
Installing the Python MONGO module
Pip Install Pymongo
View after installation
PIP List
Module reference
Import Pymongo
Establish a connection
Import Pymongo from Import = mongoclient ('localhost', 27017)#client = mongoclient ( ' mongodb://localhost:27017 ')
Accessing the database
The users of the database test currently in use
db == db.users# or db = client[' users ']
Insert Document
A document is a row, and a collection is a table
A Insert_one ()
User1 = {"name":"li8","Age": 8 = users.insert_one (user1)print('oneinsert:{0}'. Format (rs.inserted_id))
Multiple Insert_many ()
User2 = {"name":"Li9"," Age": 9}user3= {"name":"li10"," Age": 10}user4= {"name":"li11"," Age": 11}user5= {"name":"li12"," Age": 12}new_result=Users.insert_many ([User2, User3, User4, User5])Print('multiple users: {0}'. Format (New_result.inserted_ids))
Retrieving documents
A Find_one ()
Usertmp = Users.find_one ({"Age":)print(usertmp)
Multiple find ()
rs = users.find ({'age': +}) for in rs: Print (TMP)
Advanced Query
rs = users.find ({'age': {"$lt": +}}). Sort (" Name") for in rs: print(TMP)
Number of statistics
Print (Users.count ())
Add index
from Import Ascending, descending Print (Users.create_index ("Age", Descending), ("name", Ascending)])
Mongoengine is an Object document Mapper (ODM), equivalent to an SQL-based object-relational mapper (ORM)
The abstraction provided by Mongoengine is class-based, and all models created are classes
Installation
Pip Install Mongoengine
Use
fromMongoengineImport*Connect ('Test', host='localhost', port=27017)ImportdatetimeclassUsers (Document): Name= Stringfield (Required=true, max_length=200) Age= Intfield (required=True) Users=Users.objects.all () forUinchUsers:Print("Name:", U.name,", Age:", U.age)
Save
fromMongoengineImport*Connect ('Test', host='localhost', port=27017)ImportdatetimeclassUsers (Document): Name= Stringfield (Required=true, max_length=200) Age= Intfield (required=True) User1=Users (Name='ZZ', Age= 11) User1.save ()Print(user1.name) user1.name='Zz11'User1.save ()Print(User1.name)
Using MongoDB in Python