MongoEngine – QuerySet方法
QuerySet对象拥有以下有用的方法来查询数据库。
first()
返回满足查询的第一个文档。以下代码将返回产品集合中第一个价格<20000的文档。
qset=products.objects(price__lt=20000)
doc=qset.first()
print ('Name:',doc.Name, 'Price:',doc.price)
输出
Name: Router Price: 2000
exclude()
这将导致提到的字段从查询集中排除。这里,Document类的to_json()方法被用来获得JSON化的Document。ProductID字段将不会出现在结果中。
for product in products.objects.exclude('ProductID'):
print (product.to_json())
输出
{"_id": {"oid": "5c8dec275405c12e3402423c"}, "Name": "Laptop", "price": 25000}
{"_id": {"oid": "5c8dec275405c12e3402423d"}, "Name": "TV", "price": 50000}
{"_id": {"oid": "5c8dec275405c12e3402423e"}, "Name": "Router", "price": 2000}
{"_id": {"oid": "5c8dec275405c12e3402423f"}, "Name": "Scanner", "price": 5000}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "Name": "Printer", "price": 12500}
fields()
使用这个方法来操作在查询集中加载哪些字段。使用字段名作为关键字参数,设置为1表示包括,0表示不包括。
for product in products.objects.fields(ProductID=1,price=1):
print (product.to_json())
输出
{"_id": {"oid": "5c8dec275405c12e3402423c"}, "ProductID": 1, "price": 25000}
{"_id": {"oid": "5c8dec275405c12e3402423d"}, "ProductID": 2, "price": 50000}
{"_id": {"oid": "5c8dec275405c12e3402423e"}, "ProductID": 3, "price": 2000}
{"_id": {"oid": "5c8dec275405c12e3402423f"}, "ProductID": 4, "price": 5000}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "ProductID": 5, "price": 12500}
在fields()方法中设置字段关键字参数为0,其作用与exclude()方法类似。
for product in products.objects.fields(price=0):
print (product.to_json())
输出
{"_id": {"oid": "5c8dec275405c12e3402423c"}, "ProductID": 1, "Name": "Laptop"}
{"_id": {"oid": "5c8dec275405c12e3402423d"}, "ProductID": 2, "Name": "TV"}
{"_id": {"oid": "5c8dec275405c12e3402423e"}, "ProductID": 3, "Name": "Router"}
{"_id": {"oid": "5c8dec275405c12e3402423f"}, "ProductID": 4, "Name": "Scanner"}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "ProductID": 5, "Name": "Printer"}
only()
这个方法的效果类似于fields()方法。只对应于关键字参数的字段将出现在查询集中。
for product in products.objects.only('Name'):
print (product.to_json())
输出
{"_id": {"oid": "5c8dec275405c12e3402423c"}, "Name": "Laptop"}
{"_id": {"oid": "5c8dec275405c12e3402423d"}, "Name": "TV"}
{"_id": {"oid": "5c8dec275405c12e3402423e"}, "Name": "Router"}
{"_id": {"oid": "5c8dec275405c12e3402423f"}, "Name": "Scanner"}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "Name": "Printer"}
sum()
该方法计算查询集中给定字段的总和。
average()
该方法计算查询集中给定字段的平均数。
avg=products.objects.average('price')
ttl=products.objects.sum('price')
print ('sum of price field',ttl)
print ('average of price field',avg)
输出
sum of price field 94500
average of price field 18900.0