Tutorial on using external engine to operate MongoDB in Python

Source: Internet
Author: User

Tutorial on using external engine to operate MongoDB in Python

Tutorial on using external engine to operate MongoDB in Python

This article mainly introduces how to use MongoDB using external engine in Python, including some tips for using Django. For more information, see

Recently, Django was picked up again, but Django does not support mongodb. However, there is a module, the runtime engine, which can implement similar encapsulation of 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

?

1

2

Easy_install pymongo # dependent Libraries

Easy_install external Engine

Basic usage

?

1

2

3

4

5

6

7

8

9

10

11

12

13

From external engine import *

From datetime import datetime

# Connecting to a database

Connect ('blog ') # connect to the local blog Database

# If you need to verify and specify the Host Name

# Connect ('blog ', host = '192. 168.3.1', username = 'root', password = '123 ')

 

# Defining classification documents

Class Categories (Document ):

'Inherit the Document class, which is a common document'

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

?

1

2

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

Cate. save () # save to database

Query and update

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

?

1

2

3

4

5

6

7

8

# 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 documents:

Cate. name = "LinuxZen"

Cate. update ()

The default query array "=" indicates in:

?

1

2

3

4

5

6

7

8

9

10

11

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 will be returned.

Posts. objects (tags = 'coding ')

ReferenceField reference field:

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

?

1

2

3

4

5

6

7

8

9

10

11

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

?

1

2

3

4

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:

?

1

2

3

4

>>> Cate = Posts. objects. all (). first (). categories

>>> Cate

 

>>> Cate. name

U'linux'

Query articles containing Linux categories

?

1

2

>>> 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:

?

1

2

3

4

5

6

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:

?

1

2

3

Class Tags (EmbeddedDocument ):

Name = StringField ()

Date = DateTimeField (default = datetime. now ())

Insert the Tags in the Posts document as follows:

?

1

2

3

4

5

6

7

8

9

10

11

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

?

1

2

3

4

5

6

7

8

9

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

# Comments-skip 5, limit 10

Page. 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.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

# Increase the value of by in the comments field of the embedded document by 1 for the document field votes of joe

Page. objects (comments_by = "joe"). update (inc _ votes = 1)

 

# Update the embedded document comments field by with the value of joe's document field votes set to 1

Page. objects (comments_by = "joe"). update (set _ votes = 1)

 

Other skills

 

# Converting query results into dictionaries

Users_dict = User. objects (). to_mongo ()

 

# Sort by date

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

 

# Sort by date in reverse order

 

User = User. 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.