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='john@example.com', first_name='John', last_name='Tao').save()
ross = User(email='ross@example.com')
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='123456@qq.com')
//对 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的更多相关文章

  1. [转]Python中的str与unicode处理方法

    早上被python的编码搞得抓耳挠腮,在搜资料的时候感觉这篇博文很不错,所以收藏在此. python2.x中处理中文,是一件头疼的事情.网上写这方面的文章,测次不齐,而且都会有点错误,所以在这里打算自 ...

  2. python中的Ellipsis

    ...在python中居然是个常量 print(...) # Ellipsis 看别人怎么装逼 https://www.keakon.net/2014/12/05/Python%E8%A3%85%E9 ...

  3. python中的默认参数

    https://eastlakeside.gitbooks.io/interpy-zh/content/Mutation/ 看下面的代码 def add_to(num, target=[]): tar ...

  4. Python中的类、对象、继承

    类 Python中,类的命名使用帕斯卡命名方式,即首字母大写. Python中定义类的方式如下: class 类名([父类名[,父类名[,...]]]): pass 省略父类名表示该类直接继承自obj ...

  5. python中的TypeError错误解决办法

    新手在学习python时候,会遇到很多的坑,下面来具体说说其中一个. 在使用python编写面向对象的程序时,新手可能遇到TypeError: this constructor takes no ar ...

  6. python中的迭代、生成器等等

    本人对编程语言实在是一窍不通啊...今天看了廖雪峰老师的关于迭代,迭代器,生成器,递归等等,word天,这都什么跟什么啊... 1.关于迭代 如果给定一个list或tuple,我们可以通过for循环来 ...

  7. python2.7高级编程 笔记二(Python中的描述符)

    Python中包含了许多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装饰器(decorator).对于大部分特性来说,这些" ...

  8. python cookbook 学习系列(一) python中的装饰器

    简介 装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象.它经常用于有切面需求的场景,比如:插入日志.性能测试.事务处理.缓 ...

  9. 用 ElementTree 在 Python 中解析 XML

    用 ElementTree 在 Python 中解析 XML 原文: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python- ...

随机推荐

  1. Aandroid 图片加载库Glide 实战(一),初始,加载进阶到实践

    原文: http://blog.csdn.net/sk719887916/article/details/39989293 skay 初识Glide 为何使用 Glide? 有经验的 Android ...

  2. 和菜鸟一起学linux之DBUS基础学习记录

    D-Bus三层架构 D-Bus是一个为应用程序间通信的消息总线系统, 用于进程之间的通信.它是个3层架构的IPC 系统,包括: 1.函数库libdbus ,用于两个应用程序互相联系和交互消息. 2.一 ...

  3. obj-c编程10:Foundation库中类的使用(6)[线程和操作队列]

    任何语言都不能避而不谈线程这个东东,虽然他是和平台相关的鸟,虽说unix哲学比较讨厌线程的说...线程不是万能灵药,但有些场合还是需要的.谈到线程就不得不考虑同步和死锁问题,见如下代码: #impor ...

  4. python实现gabor滤波器提取纹理特征 提取指静脉纹理特征 指静脉切割代码

    参考博客:https://blog.csdn.net/xue_wenyuan/article/details/51533953 https://blog.csdn.net/jinshengtao/ar ...

  5. Vi 操作命令

    进入vi的命令  vi filename :打开或新建文件,并将光标置于第一行首  vi +n filename :打开文件,并将光标置于第n行首  vi + filename :打开文件,并将光标置 ...

  6. P3370 【模板】字符串哈希

    题目描述 如题,给定N个字符串(第i个字符串长度为Mi,字符串内包含数字.大小写字母,大小写敏感),请求出N个字符串中共有多少个不同的字符串. 输入输出格式 输入格式: 第一行包含一个整数N,为字符串 ...

  7. [C#]使用 C# 编写自己的区块链挖矿算法

    [C#] 使用 C# 编写自己区块链的挖矿算法 文章原文来自:Code your own blockchain mining algorithm in Go! ,原始文章通过 Go 语言来实现的,这里 ...

  8. Codeforces Round #479 (Div. 3) C. Less or Equal

    题目地址:http://codeforces.com/contest/977/problem/C 题解:给一串数组,是否找到一个数x,找到k个数字<=x,找到输出x,不能输出-1.例如第二组,要 ...

  9. linux服务器上部署项目,同时运行两个或多个tomcat

    在阿里云服务器上部署项目的时候,想使用阿里云提供的负载均衡服务并创建两个监听(如图), 但需要一台服务器提供两个端口,于是就请教前辈并查询资料,得知: 一台服务器提供两个端口,有两种方式: 1.一个t ...

  10. C#本质论笔记

    第一章 C#概述 1.1 Helo,World 学习一种新语言最好的办法就是动手写程序.        C#编译器创建的.exe程序是一个程序集(Assembly),我们也可以创建能由另一个较大的程序 ...