MongoEngine - 查詢集方法



QuerySet 物件擁有以下用於查詢資料庫的有用方法。

first()

返回滿足查詢的第一個文件。以下程式碼將返回 products 集合中第一個價格小於 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 格式版本。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
廣告

© . All rights reserved.