Python中使用MongoEngine2

Posted zhouxinfei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中使用MongoEngine2相关的知识,希望对你有一定的参考价值。

mongoengine基本用法实例:

from mongoengine import *
from datetime import datetime

#连接数据库:test
# connect(‘test‘)    # 连接本地test数据库
connect(test, host=127.0.0.1, port=27017, username=test, password=test)

# Defining our documents
# 定义文档user,post,对应集合user,post
class User(Document):
    # required为True则必须赋予初始值
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)
    date = DateTimeField(default=datetime.now(), required=True)

# Embedded documents,it doesn’t have its own collection in the database
class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)

class Post(Document):
    title = StringField(max_length=120, required=True)
    # ReferenceField相当于foreign key
    author = ReferenceField(User)
    tags = ListField(StringField(max_length=30))
    comments = ListField(EmbeddedDocumentField(Comment))
    # 允许继承
    meta = {allow_inheritance: True}

class TextPost(Post):
    content = StringField()

class ImagePost(Post):
    image_path = StringField()

class LinkPost(Post):
    link_url = StringField()

# Dynamic document schemas:DynamicDocument documents work in the same way as Document but any data / attributes set to them will also be saved
class Page(DynamicDocument):
    title = StringField(max_length=200, required=True)
    date_modified = DateTimeField(default=datetime.now())

 

添加数据

john = User(email=[email protected], first_name=John, last_name=Tao).save()
ross = User(email=[email protected])
ross.first_name = Ross
ross.last_name = Lawley
ross.save()

comment1 = Comment(content=Good work!,name = LindenTao)
comment2 = Comment(content=Nice article!)
post0 = Post(title = post0,tags = [post_0_tag])
post0.comments = [comment1,comment2]
post0.save()

post1 = TextPost(title=Fun with MongoEngine, author=john)
post1.content = Took a look at MongoEngine today, looks pretty cool.
post1.tags = [mongodb, mongoengine]
post1.save()

post2 = LinkPost(title=MongoEngine Documentation, author=ross)
post2.link_url = http://docs.mongoengine.com/
post2.tags = [mongoengine]
post2.save()

# Create a new page and add tags
page = Page(title=Using MongoEngine)
page.tags = [mongodb, mongoengine]
page.save()

 

创建了三个集合:user,post,page

 

 
技术分享图片
 

 

 
技术分享图片
 

 

 
技术分享图片
 

查看数据

# 查看数据
for post in Post.objects:
    print post.title
    print = * len(post.title)

    if isinstance(post, TextPost):
        print post.content

    if isinstance(post, LinkPost):
        print Link:, post.link_url

# 通过引用字段直接获取引用文档对象    
for post in TextPost.objects:
    print post.content
    print post.author.email  
au = TextPost.objects.all().first().author
print au.email

# 通过标签查询    
for post in Post.objects(tags=mongodb):
    print post.title   
num_posts = Post.objects(tags=mongodb).count()
print Found %d posts with tag "mongodb" % num_posts

# 多条件查询(导入Q类) 
User.objects((Q(country=uk) & Q(age__gte=18)) | Q(age__gte=20))   

# 更新文档
ross = User.objects(first_name = Ross)
ross.update(date = datetime.now())
User.objects(first_name=John).update(set__email=[email protected])
//对 lorem 添加商品图片信息
lorempic = GoodsPic(name=l2.jpg, path=/static/images/l2.jpg)
lorem = Goods.objects(id=575d38e336dc6a55d048f35f)
lorem.update_one(push__pic=lorempic)
# 删除文档
ross.delete()

 

备注

ORM全称“Object Relational Mapping”,即对象-关系映射,就是把关系数据库的一行映射为一个对象,也就是一个类对应一个表,这样,写代码更简单,不用直接操作SQL语句。

以上是关于Python中使用MongoEngine2的主要内容,如果未能解决你的问题,请参考以下文章

Python 向 Postman 请求代码片段

在 Python 多处理进程中运行较慢的 OpenCV 代码片段

使用 Python 代码片段编写 LaTeX 文档

13 个非常有用的 Python 代码片段

你如何在 python 中处理 graphql 查询和片段?

python 用于数据探索的Python代码片段(例如,在数据科学项目中)