Tutorial on using external engine to operate MongoDB in Python

Source: Internet
Author: User
This article mainly introduces the tutorial on using external engine to operate MongoDB in Python, including some tips for using Django. if you need it, you can refer to the following to pick up Django again recently, but Django does not support mongodb, however, there is a module, the runtime engine, which can implement encapsulation similar to the Django Model. however, there are almost no Chinese documents for the engine, and some of them are short introductions and usage. next I will share some of my notes recorded during use, which may be a bit messy. for more information, see.
Install external engine

Easy_install pymongo # dependent Library easy_install external engine

Basic usage

From external engine import * from datetime import datetime # connect to database connect ('blog ') # connect to local blog database # If you need to verify and specify the host name # connect ('blog ', host = '2017. 168.3.1 ', username = 'root', password = '000000') # define the category Document class Categories (Document):' inherits the Document class, for common documents 'name = StringField (max_length = 30, required = True) artnum = IntField (default = 0, required = True) date = DateTimeField (default = datetime. now (), required = True)

It is similar to Django's model, so it does not explain anything.
Insert

Cate = Categories (name = "Linux") # if required is True, the initial value must be assigned. if default is available, the default value cate. save () is used to grant the initial value to the database. # save to the database.

Query and update

The document class has an objects attribute. We use it to query the database.

# Return the list of all document objects in the set. cate = Categories. objects. all () # return the list of all document objects that meet the query criteria cate = Categories. objects (name = "Python") # Update the queried document: cate. name = "LinuxZen" cate. update ()
The default query array "=" indicates 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) # All documents whose tags contain coding are returned. objects (tags = 'coding ')


ReferenceField reference field:

You can use the reference field to directly obtain the document referenced by the reference field:

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()

Directly retrieve referenced document objects using referenced fields

Generally, a list is returned for a document query (although there is only one result). to obtain a document object, you can use the index to obtain the first document object. However, we recommend that you use first () to obtain the first one:

>>> cate = Posts.objects.all().first().categories>>> cate>>> cate.name

U'linux'

Query articles containing Linux categories

>>> cate = Categories.objects(name="Linux").first()>>> Posts.objects(categories=cate)

EmbeddedDocument embedded document

The document class that inherits EmbeddedDocument is embedded document. the embedded document is used to embed the EmbeddedDocumentField field of other documents. for example, if the tags field in the preceding example is changed to embedded document, the Posts document class can be changed to the following method:

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())

Insert the 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.nameLinuxzenmysite

Time period query

 start = datetime(int(year), int(month), 1) if int(month) + 1 > 12:  emonth = 1  eyear = int(year) + 1 else:  emonth = int(month) + 1  eyear = int(year) end = datetime(eyear, emonth, 1) articles = Posts.objects(date__gte=start, date__lt=end).order_by('-date')

Parts

Slice for sharding

# Comments-skip 5, limit 10Page. objects. fields (slice _ comments = [5, 10]) # You can also use index value sharding # limit 5 users = User. objects [: 5] # skip 5 users = User. objects [5:] # skip 10, limit 15 users = User. objects [10: 15]

Use the original statement to query

To use the original pymongo query method, use the _ raw _ operator Page. objects (raw = {'tags': 'coding'}) to use the $ inc and $ set operators.

# Update the embedded document comments field by to add 1Page to the document field votes of joe. objects (comments_by = "joe "). update (inc _ votes = 1) # update the file field votes of the embedded document comments field by with the value of joe to 1Page. objects (comments_by = "joe "). update (set _ votes = 1) Other Tips # Convert query results to the dictionary users_dict = User. objects (). to_mongo () # sort by date by user = User. objects. order_by ("date") # user = User in descending order of date. objects. order_by ("-date ")

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.