MongoDB database, which is used by MongoDB Engine
1. initialize the connection
If our MongoDB runs directly on a local computer, you can use the following code to connect to the MongoDB database on the computer:
from mongoengine import *
Connect ('database name ')
If MongoDB is not running on a local computer, you need to specify the ip address and port:
from mongoengine import *
Connect ('database name', host = '192. 168.2.12 ', port = 192) # note that the port number is a number not a string.
2. Definition document
Define a class. Here we take personal information as an example. This class inherits the Document class of movie engine. Note that the class name "People" corresponds to the Set Name in MongoDB. Each variable in the class corresponds to the column name in each record.
From external engine import * class People (Document): name = StringField (required = True) # note that all variables with required = True are written, required parameters during class initialization. Age = IntField (required = True) sex = StringField (required = True) salary = IntField () # Here the IntField or StringField corresponds to the Data Type
3. Create an object
Initialize the People class and create an object:
kingname = People(name='kingname', age=18, sex='male', salary=99999)
Note that the parameter name, age, and sex cannot be omitted, but salary can be omitted.
kingname.save()
Of course, we can also write:
kingname = People(name='kingname', age=18, sex='male')kingname.salary = 99999kingname.save()
After the information is saved, if you want to modify the information, you can write as follows:
kingname.age = 22kingname.save()
In this way, the age is changed to 22 years old. It is much simpler than pymongo.
4. Read objects
What if I want to read all user information? Very simple:
for person in People.objects: print(person.name) print(person.age) print(person.sex)
Conditional search is also very simple. Just add a parameter after People. objects. For example, search for all People aged 22:
for person in People.objects(age=22): print(person.name)
I want to know if I want to write the information into the database. You can use RoboMongo to read the database and see if there is a collection called People, which contains the data we added.
5. delete records
If you want to delete a record, find the record and call the delete () method:
kingname_list = People.objects(name='kingname')for kingname in kingname_list: kingname.delete()
Example
From external engine import * connect ('people') # link to an existing database class people (Document): name = StringField (required = True) age = IntField (required = True) sex = StringField (required = True) salary = IntField () chenxiao = People (name = 'chenxio', age = 26, sex = 'male', salary = 99999) chenxiao. save () ''' query ''' malelist = People. objects (sex = 'male') for man in malelist: print man. name >>> chenxiao