Recently picked up Django, but Django does not support MongoDB, but there is a module mongoengine that can implement a Django model-like package. But Mongoengine's Chinese documents are almost none, Some of them are short sentences to introduce and use. I'll share some of the notes I've recorded during my use, which may be a bit messy. You can refer to it for a moment.
Installing Mongoengine
# Dependent library Easy_install mongoengine
Basic use
fromMongoengineImport* fromDatetimeImportdatetime#connecting to a databaseConnect'Blog')#Connect to the local blog database#To verify and specify a host name#Connect (' blog ', host= ' 192.168.3.1 ', username= ' root ', password= ' 1234 ')#Defining a classification documentclassCategories (Document):'inherit document class, for normal documents'name= Stringfield (max_length=30, required=True) Artnum= Intfield (default=0, required=True) Date= Datetimefield (Default=datetime.now (), required=true)
It's similar to the Django model, so it doesn't explain anything.
Insert
Cate = Categories (name="Linux") # If required is true the initial value must be given, if there is default, Assign initial value to save to database using default value #
Queries and Updates
The document class has a objects property. We use it to query the database.
#returns a list of all document objects in the collectionCate =Categories.objects.all ()#returns a list of all document objects that match the results of the query criteriaCate = Categories.objects (name="Python")#update the query to the document:Cate.name ="Linuxzen"cate.update () query array default query array"="the meaning of the representation is in:classPosts (Document): ArtID= Intfield (required=True) Title= Stringfield (max_length=100, required=True) Content= Stringfield (required=True) Author=Referencefield (User) tags= ListField (Stringfield (max_length=20, required=true), required=True) Categories= Referencefield (Categories), required=True) Comments= Intfield (default=0, required=True)#all tags containing coding documents will be returned.Posts.objects (tags='Coding')
Referencefield reference fields:
The document referenced by the Reference field can be obtained directly from the document by referencing the field:
class Categories (Document): = Stringfield (max_length=30, required=true) = Intfield (default=0, required=true) = Datetimefield (Default=datetime.now (), required=True)class Posts (Document): = Stringfield (max_length=100, required=true) = Stringfield (required=true) = ListField (Stringfield (max_length=20, required=true), required=True) = Referencefield (Categories)
Insert Reference Field
Cate =categories (name="Linux"= Posts (title="linuxzen.com ", content="linuxzen.com", tags=["Linux", " Web "], categories=Cate) post.save ()
Get a reference Document object directly from a reference field
A generic document query returns a list (although there is only one result), and we want to get a document object that can use the index to get the first document object, but Mongoengine recommends using first () to get one:
>>> cate = Posts.objects.all (). First (). Categories>>> cate>>> Cate.nameu'Linux'
Query for articles that contain Linux classifications
>>> cate = categories.objects (name="Linux"). First ()>>> Posts.objects (Categories=cate)
Embeddeddocument Embedding Documents
The document class that inherits Embeddeddocument is the embedded document, the embedded document is used to embed the Embeddeddocumentfield field of other documents, for example, if the tags field of the above example is changed into an embedded document, the posts document class can be changed to the following way:
class Posts (Document): = Stringfield (max_length=100, required=true) = Stringfield (required=true) = ListField ( Embeddeddocumentfield ('Tags') required=True) = Referencefield ( Categories)
You also need to add a tags embedded in the document class:
Class== Datetimefield (Default=datetime.now ())
We insert tags in the posts document as follows
>>> tag = tags (name="Linuxzen")>>> post = Posts (title="linuxzen.com", content="linuxzen.com", Tags=[tag], categories=Cate)>>> tag = tags (name="MySite")>>>post.tags.append (TAG)>>>Post.save ()>>> tags =Post.tags>>> forTaginchTags:PrintTag.namelinuxzenmysite
Time period Query
Start = datetime (int (year), Int (month), 1) if Int (month) + 1 > := 1
= Int (year) + 1 else: = Int (month) + 1 = int (year) = DateTime (Eyear, Emonth, 1) = Posts.objects (Date__gte=start, Date__lt=end). Order_by (' -date ')
Sharding
Slice for sharding
# Comments-skip 5, limit ten Page.objects.fields (slice__comments=[5)# can also use index value shard # Limit 5 Users = User.objects[:5]# Skip 5users = user.objects[5:]# Skip Limitusers = user.objects[10:15]
Querying with the original statement
If you want to use the original Pymongo query method you can use the raw operator page.objects (raw={' tags ': ' coding ') using the $inc and $set operators
# Update the embedded document Comments field by the value of Joe's document field votes increase by 1 Page.objects (comments_by="Joe"). Update (Inc__votes=1)# Update the embedded document Comments field by the value of Joe for the document field votes set to 1page.objects (comments_by="Joe"). Update (Set__votes=1)
Other Tips
# The query results are converted to dictionaries users_dict = user.objects (). To_mongo ()# sort, by date User = User.objects.order_by ("date")# reversed by Date = User.objects.order_by ("-date")
Using MongoEngine3 in Python