Mongoengine 简明教程
MongoEngine - Query Operators
除了使用 = 操作符检查是否相等外,MongoEngine 中还定义了以下逻辑操作符。
In addition to = operator to check equality, the following logical operators are defined in MongoEngine.
ne |
not equal to |
lt |
less than |
lte |
less than or equal to |
gt |
greater than |
gte |
greater than or equal to |
not |
negate a standard check, may be used before other operators |
in |
value is in list |
nin |
value is not in list |
mod |
value % x == y, where x and y are two provided values |
all |
every item in list of values provided is in array |
size |
the size of the array is |
exists |
value for field exists |
这些运算符必须附加到带有双下划线 __ 的字段名。
These operators must be attached to field name with double underscore __.
要使用大于运算符 (gt),使用以下格式 -
To use greater than (gt) operator, use the following format −
#using greater than operator
for product in products.objects(price__gt=10000):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
Output
ID: 1 Name: Laptop Price: 25000
ID: 2 Name: TV Price: 50000
ID: 5 Name: Printer Price: 12500
in 运算符类似于 Python 的 in 运算符。对于与列表中名称相匹配的产品名称,使用以下代码 -
The in operator is like Python’s in operator. For name of product matching with names in list, the following code is used −
for product in products.objects(Name__in=['TV', 'Printer']):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
Output
ID: 2 Name: TV Price: 50000
ID: 5 Name: Printer Price: 12500
您可以使用以下运算符作为应用于查询的正则表达式的快捷方式 -
You can use following operators as shortcut for regex expressions for applying filter to queries −
exact |
string field exactly matches value |
iexact |
string field exactly matches value (case insensitive) |
contains |
string field contains value |
icontains |
string field contains value (case insensitive) |
startswith |
string field starts with value |
istartswith |
string field starts with value (case insensitive) |
endswith |
string field ends with value |
iendswith |
string field ends with value (case insensitive) |
match |
performs an $elemMatch so you can match an entire document within an array |
例如,以下代码将打印名称中包含 'o' 的产品详细信息 -
For example, the following code prints product details for name containing ‘o’ in name −
for product in products.objects(Name__contains='o'):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
Output
ID: 1 Name: Laptop Price: 25000
ID: 3 Name: Router Price: 2000
在另一个字符串查询示例中,以下代码显示以 'er' 结尾的名称 -
In another example of string query, the following code displays name ending with ‘er’−
for product in products.objects(Name__endswith='er'):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)