PyMongo是一個(gè)低級(jí)的MongoDB的Python驅(qū)動(dòng)器(我一般稱為客戶端)巩趁,它封裝了 MongoDB API两嘴,并通過JSON與MongoDB通信扔字,PyMongo將MongoDB的數(shù)據(jù)映射成Python的內(nèi)置類型。
MongoEngine 是一個(gè)Document-Object Mapper (想一下ORM, 但它是針對(duì)文檔型數(shù)據(jù)庫(kù))捌显,Python通過它與MongoDB交互吠式。你可能會(huì)說那PyMongo也是ORM啊陡厘,在Python中一切都是對(duì)象,但我們所說的ORM中的Object在指Python中的自定義類奇徒,而不是內(nèi)置類型雏亚。MongoEngine或MongoKit將MongoDB的數(shù)據(jù)映射成自定義類實(shí)例,它們都是基于PyMongo的摩钙。
我們可以跟關(guān)系型數(shù)據(jù)庫(kù)的Python客戶端MySQLdb罢低,以及ORM SQLAlchemy/Django ORM比較一下,PyMongo相當(dāng)于MySQLdb胖笛,MongoEngine相當(dāng)于SQLAlchemy网持,SQLAlchemy是基于MySQLdb之上的,MongoEngine是基于PyMongo的长踊。
MongoEngine是一個(gè)ORM
安裝
pip install mongoengine
連接
from mongoengine import *
connect(‘mongoengine_test’,host=’localhost’,port=27017)
定義文檔中的存放數(shù)據(jù)的字段,還要繼承Document類,在這里定義好模型限制,以后save的時(shí)候做驗(yàn)證用得著
import datetime
class Post(Document):
title = StringField(required=True, max_length=200)
content = StringField(required=True)
author = StringField(required=True, max_length=50)
published = DateTimeField(default=datetime.datetime.now)
required:設(shè)置必須功舀;
default:如果沒有其他值給出使用指定的默認(rèn)值
unique:確保集合中沒有其他document有此字段的值相同
choices:確保該字段的值等于數(shù)組中的給定值之一
4.完整的插入保存過程
from mongoengine import *
connect('mongoengine_test',host='localhost',port=27017)
import datetime
class Post(Document):
title = StringField(required=True, max_length=200)
content = StringField(required=True)
author = StringField(required=True, max_length=50)
published = DateTimeField(default=datetime.datetime.now)
post_1 = Post(
title='Sample Post',
content='Some engaging',
author='scott'
)
post_1.save()
print(post_1.title)
post_1.title = '張昆'
post_1.save()
print(post_1.title)
mongoengine基本用法實(shí)例:
from mongoengine import *
from datetime import datetime
#連接數(shù)據(jù)庫(kù):test
# connect('test') # 連接本地test數(shù)據(jù)庫(kù)
connect('test', host='127.0.0.1', port=27017, username='test', password='test')
# Defining our documents
# 定義文檔user,post,對(duì)應(yīng)集合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相當(dāng)于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())
添加數(shù)據(jù)
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()
創(chuàng)建了三個(gè)集合:user,post,page
查看數(shù)據(jù)
# 查看數(shù)據(jù)
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
# 通過引用字段直接獲取引用文檔對(duì)象
for post in TextPost.objects:
print post.content
print post.author.email
au = TextPost.objects.all().first().author
print au.email
# 通過標(biāo)簽查詢
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
# 多條件查詢(導(dǎo)入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')
//對(duì) 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”,即對(duì)象-關(guān)系映射身弊,就是把關(guān)系數(shù)據(jù)庫(kù)的一行映射為一個(gè)對(duì)象辟汰,也就是一個(gè)類對(duì)應(yīng)一個(gè)表,這樣阱佛,寫代碼更簡(jiǎn)單帖汞,不用直接操作SQL語句。
鏈接:
https://blog.csdn.net/u011845833/article/details/51151434
https://blog.csdn.net/u013205877/article/details/76037540