search
HomeBackend DevelopmentPython Tutorial在Python中使用mongoengine操作MongoDB教程

最近重新拾起Django,但是Django并不支持mongodb,但是有一个模块mongoengine可以实现Django Model类似的封装.但是mongoengine的中文文档几乎没有,有的也是简短的几句介绍和使用.下面我就分享一下我在使用过程中所记录下的一些笔记,可能有点乱.大家可以参考一下.
安装mongoengine

easy_install pymongo # 依赖库
easy_install mongoengine

基本使用

from mongoengine import *
from datetime import datetime
# 连接数据库
connect('blog') # 连接本地blog数据库
# 如需验证和指定主机名
# connect('blog', host='192.168.3.1', username='root', password='1234')

# 定义分类文档
class Categories(Document):
 ' 继承Document类,为普通文档 '
 name = StringField(max_length=30, required=True)
 artnum = IntField(default=0, required=True)
 date = DateTimeField(default=datetime.now(), required=True)

和Django的model使用很类似,所以也不解释什么.
插入

cate = Categories(name="Linux") # 如果required为True则必须赋予初始值,如果有default,赋予初始值则使用默认值
cate.save() # 保存到数据库

查询和更新

文档类有一个 objects 属性.我们使用它来查询数据库.

# 返回集合里的所有文档对象的列表
cate = Categories.objects.all()

# 返回所有符合查询条件的结果的文档对象列表
cate = Categories.objects(name="Python")
# 更新查询到的文档:
cate.name = "LinuxZen"
cate.update()
查询数组 默认查询数组"="代表的意思是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)

# 将会返回所有tags包含coding的文档
Posts.objects(tags='coding')


ReferenceField 引用字段:

通过引用字段可以通过文档直接获取引用字段引用的那个文档:

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)

插入引用字段

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

通过引用字段直接获取引用文档对象

一般文档查询会返回一个列表(尽管只有一个结果),我们想要获得一个文档对象可以使用索引获取第一个文档对象,但是mongoengine建议使用first()来获取第一个:

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

>>> cate.name

u'Linux'

查询包含Linux分类的文章

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

EmbeddedDocument 嵌入文档

继承EmbeddedDocument的文档类就是嵌入文档,嵌入文档用于嵌入其他文档的EmbeddedDocumentField 字段,比如上面例子的tags字段如果改成嵌入文档的话可以将Posts文档类改成如下方式:

class Posts(Document):

 title = StringField(max_length=100, required=True)
 content = StringField(required=True)
 tags = ListField(EmbeddedDocumentField('Tags')required=True)
 categories = ReferenceField(Categories)

还需要添加一个Tags嵌入文档类:

class Tags(EmbeddedDocument):
name = StringField()
date = DateTimeField(default=datetime.now())

我们像如下方式插入Posts文档中的Tags

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

时间段查询

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

分片

slice用于分片

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

# 也可以使用索引值分片

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

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

# skip 10, limit 15
users = User.objects[10:15]

使用原始语句查询

如果想使用原始的pymongo查询方式可以使用__raw__操作符 Page.objects(raw={'tags':'coding'}) 使用$inc和$set操作符

# 更新嵌入文档comments字段by的值为joe的文档字段votes增加1
Page.objects(comments_by="joe").update(inc__votes=1)

# 更新嵌入文档comments字段by的值为joe的文档字段votes设置为1
Page.objects(comments_by="joe").update(set__votes=1)

其他技巧

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

# 排序,按日期排列
user = User.objects.order_by("date")

# 按日期倒序

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

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools