Use the Mongoengine operation MongoDB Tutorial in Python _python

Source: Internet
Author: User
Tags comments mongodb mongodb tutorial

Recently picked up Django, but Django does not support MongoDB, but there is a module mongoengine can implement the Django model similar encapsulation. But Mongoengine's Chinese documents are almost never Some is also a brief introduction and use. I'll share some of the notes I've recorded in the course of my use, which may be a bit messy. You can refer to it.
Install Mongoengine

Easy_install Pymongo # Dependent library
Easy_install mongoengine

Basic use

From mongoengine Import * from
datetime import datetime
# Connect to database connect
(' blog ') # connect the local blog database
# To verify and specify host name
# connect (' blog ', host= ' 192.168.3.1 ', username= ' root ', password= ' 1234 ')

# define category document
class Categories (document):
 ' Inherit the document class, for normal document '
 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, you must give the initial value, and if there is default, give the initial value to use the Defaults
cate.save () # to save to the database

Querying and updating

The document class has a objects property. We use it to query the database.

# Returns a list of all document objects in the collection
cate = Categories.objects.all ()

# Returns a list of all the document objects that match the results of the query
cate = categories.objects (name= "Python")
# Update the document that is queried:
cate.name = "Linuxzen"
cate.update ()
The query array default query array "=" means in:
Class Posts (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)

# will return all tags containing coding document
posts.objects (tags= ' coding ')


Referencefield Reference field:

By referencing a field, you can get directly to the document referenced by the Reference field through the document:

Class Categories (Document):
 name = Stringfield (max_length=30, required=true)
 artnum = Intfield (default=0, required=true)
 date = Datetimefield (Default=datetime.now (), required=true)

class Posts (Document):

 title = Stringfield (max_length=100, required=true)
 content = Stringfield (required=true)
 tags = ListField ( Stringfield (max_length=20, required=true), required=true)
 categories = Referencefield (categories)

Insert Reference Field

Cate =categories (name= "Linux")
Cate.save ()
post = Posts (title= "linuxzen.com", content= "linuxzen.com", tags=["Linux", "web"], categories=cate)
Post.save ()

To 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 the number one:

>>> cate = Posts.objects.all (). A (). Categories
>>> Cate

>>> cate.name

U ' Linux '

Query for articles that contain Linux classifications

>>> cate = categories.objects (name= "Linux"). A ()
>>> posts.objects (categories=cate)

Embeddeddocument Embedded Documents

An inherited Embeddeddocument document class is an embedded document that embeds a document in a Embeddeddocumentfield field that embeds other documents, such as the tags field in the example above, which can be changed to the posts document class if it is converted to an embedded document:

Class Posts (Document):

 title = Stringfield (max_length=100, required=true)
 content = Stringfield (required= True)
 tags = ListField (Embeddeddocumentfield (' tags ') required=true)
 categories = Referencefield ( Categories)

You also need to add a tags embedded document class:

Class Tags (embeddeddocument):
name = Stringfield ()
date = 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
>>> for tag in tags:
print tag.name

Linuxzen
MySite

Time period Query

 Start = datetime (int (year), Int (month), 1)
 if INT (month) + 1 >:
  emonth = 1
  eyear = Int (year) + 1
   
    else:
  emonth = Int (month) + 1
  eyear = Int (year) End
 = DateTime (Eyear, Emonth, 1)
 articles = Posts.obj ECTS (Date__gte=start, Date__lt=end). order_by ('-date ')


   

Sharding

Slice for slicing

# comments-skip 5, limit
Page.objects.fields (slice__comments=[5, ten])

# can also use indexed value fragmentation

# limit 5
users = User.objects[:5]

# skip 5
users = user.objects[5:]

# Skip, limit
users = user.objects[10:15]

Query with original statement

If you want to use the original Pymongo query method, you can use the coding and $INC operators using the __raw__ operator page.objects (raw={' tags ': ' $set '})

# Update embedded document Comments field by the value of Joe's document field votes increased by 1
page.objects (comments_by= "Joe"). Update (Inc__votes=1)

# Update embedded Document comments The document field votes with Joe is set to 1
page.objects (comments_by= "Joe"). Update (Set__votes=1)

Other tips

#查询结果转换成字典
users_dict = user.objects (). To_mongo ()

# sorted, by date
User = User.objects.order_by (" Date ")

# Reverse by date

user = User.objects.order_by ("-date ")

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.