MongoEngine 中的Document类和QuerySet 类

2017-09-19 0 By admin

我们在Python 编程中,在MongoEngine 模块中使用到的最多的类就是文档类(Document)和执行类(QuerySet)了。以下我们介绍一下这两个类的使用方法并提供示例。

一、Document 类

1.1、定义文档模式

class User(Document):
name = StringField()
address = StringField()
age = IntField()

1.2、写入数据

创建User对象,使用save()保存
Handler = User(name=”james”,address=”china”,”age”=12).save()
也可以使用属性语句
Handler = User(name=”james”)
Handler.address=”China”
Handler.age=12
Handler.save()

二、QuerySet 类

MongoEngine框架中每个文档Document都有默认objects属性。这个属性是queryset类,用于访问数据。
默认查询集,构建查询并处理从查询返回的一组结果。包装一个MongoDB游标,提供Document对象作为结果。
在处理数据上和Document类直接处理存在着区别。

2.1、数据插入

insert()插入的数据必须是文档类型;可以多条数据一起插入;
User.objects.insert([User(name="zhang",sex=1),User(name="liu",sex=2)])

2.2、删除|修改|查找

for user in User.objects(sex=1):
#查询处理
print user.name
#删除数据
user.delete()
o

#更新数据
user.sex = 2
user.save()

2.3、对字段数值去重

User.objects.distinct("name")

2.4、部分方法列表

all() 返回所有文档。
all_fields() 包括所有字段。重置以前所有.only()或.exclude()的调用。
average(field) 平均值超过指定字段的值
batch_size(size) 限制单个批次返回的文档数量(每个批次都需要往返服务器)。
comment(text) Add a comment to the query.
count(with_limit_and_skip=False) Count the selected elements in the query.
delete(write_concern=None, _from_doc_delete=False, cascade_refs=None) Delete the documents matched by the query.
distinct(field) 像mysql group by ;Return a list of distinct values for a given field.
exclude(*fields) Opposite to .only(), exclude some document’s fields.
exec_js(code, *fields, **options) Execute a Javascript function on the server.
fields(_only_called=False, **kwargs) Manipulate how you load this document’s fields. Used by .only() and .exclude() to manipulate which fields to retrieve. If called directly, use a set of kwargs similar to the MongoDB projection document.
filter(*q_objs, **query)
first() Retrieve the first object matching the query.
from_json(json_data) Converts json data to unsaved objects
limit(n) Limit the number of returned documents to n. This may also be achieved using array-slicing syntax (e.g. User.objects[:5]).
modify (upsert=False, full_response=False, remove=False, new=False, **update)Update and return the updated document.
next() Wrap the result in a Document obje
only(*fields) Load only a subset of this document’s fields.
order_by(*keys) Order the QuerySet by the keys. The order may be specified by prepending each of the keys by a + or a -. Ascending order is assumed. If no keys are passed, existing ordering is cleared instead.
skip(n) Skip n documents before returning the results. This may also be achieved using array-slicing syntax (e.g. User.objects[5:]).
sum(field) Sum over the values of the specified field.
update(upsert=False, multi=True, write_concern=None, full_result=False, **update) Perform an atomic update on the fields matched by the query.
update_one(upsert=False, write_concern=None, **update) Perform an atomic update on the fields of the first document matched by the query.