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. ROS探索总结(十二)——坐标系统

    在机器人的控制中,坐标系统是非常重要的,在ROS使用tf软件库进行坐标转换. 相关链接:http://www.ros.org/wiki/tf/Tutorials#Learning_tf 一.tf简介 ...

  2. 一个CSS背景颜色问题

    div{ background: rgba(0,0,0,.1);     background-color: #19FFFFFF; } 安卓下会显示上面的透明颜色,而在iOS上则显示下面的颜色,并且其 ...

  3. twisted高并发库transport函数处理数据包的些许问题

    还是在学校时间比较多, 能够把时间更多的花在学习上, 尽管工作对人的提升更大, 但是总是没什么时间学习, 而且工作的气氛总是很紧凑, 忙碌, 少了些许激情吧.适应就好了.延续着之前对twisted高并 ...

  4. CF959F

    题目大意:给定n个数,有Q次询问,每次询问由两个数l,x组成,表示前缀[1,l]构成的子序列有多少异或起来为x,个数%1e9+7 做法:考虑一个由x个数构成的线性基,如果这个线性基由Y个数构成,可以通 ...

  5. C#解析json的几种方式

    json格式的数据是javascript原生的一种数据格式,比xml更简洁. 它有两种形式:json对象和json对象数组. 在此之前,有必要解释几个基本概念: json字符串,就是string,它一 ...

  6. WSGI及gunicorn指北(二)

    pyg0已经大概了解了wsgi.现在他决定深入探索他们实际在生产环境里用到的web 服务器 -gunicorn. 先来看看官网的介绍:Gunicorn 是一个运行在Unix上的python WSGI ...

  7. Flask框架之 --- 我的第一个个人网站(雏形)

    现在还是个静态网站 , 而且这里的Flask也只是起到了提供虚拟web服务器的作用  , 下一步是实现数据库的连接 , 实现简单的动态访问.

  8. python---haproxy---文件操作

    haproxy 文件操作,操作属于简单操作,不复杂 # -*- coding:utf-8 -*- # LC def search(*args): #查找Haproxy文件中的服务器 list1 = [ ...

  9. 新一代大数据处理引擎 Apache Flink

    https://www.ibm.com/developerworks/cn/opensource/os-cn-apache-flink/index.html 大数据计算引擎的发展 这几年大数据的飞速发 ...

  10. Codeforces Round #479 (Div. 3) A. Wrong Subtraction

    题目网址:http://codeforces.com/contest/977/problem/A 题解:给你一个数n,进行k次变换,从末尾开始-1,512变成511,511变成510,510会把0消掉 ...