由 neevop 三月 12, 2023
构建查询
在mongosh中我们使用find()在数据中查询匹配多个项目,在mongoengine也有类似的接口。
db.table_catalogue.find({stage_result: 'Passed'})
passed_stages = TEST.objects(stage_result='Passed')
在查询语句中,除了使用等于号,还可以使用其他运算符查询一定跨度范围内的文档。
db.Users.find({age: {'$lte': 18}})
db.Users.find({age: {'$lte': 18, '$gt': 6}})
mongoengine中运算符的使用为双下划线。
# Only find users whose age is 18 or less
young_users = Users.objects(age__lte=18)
范围查询运算符
$lt—— 小于 (less than)$gt—— 大于 (greater than)$lte—— 小于等于 (less than or equal to)$gte—— 大于等于 (greater than or equal to)
集合运算符
$in—— 引用集合包含任意参数,则匹配$all—— 引用集合包含所有参数,则匹配nin—— 引用集合不包含任意参数,则匹配 (value is not in list)
布尔运算符
$ne—— 不匹配参数条件(not equal to)not—— 不匹配结果or—— 或nor—— 所有条件都不and—— 所有条件都exists—— 判断元素是否存在
数组运算符
size—— the size of the array iselemMatch—— 如果提供的所有词语在相同的子文档中,则匹配
对于字符串字段查询的运算符有:
exact– string field exactly matches valueiexact– string field exactly matches value (case insensitive)contains– string field contains valueicontains– string field contains value (case insensitive)startswith– string field starts with valueistartswith– string field starts with value (case insensitive)endswith– string field ends with valueiendswith– string field ends with value (case insensitive)wholeword– string field contains whole wordiwholeword– string field contains whole word (case insensitive)regex– string field match by regexiregex– string field match by regex (case insensitive)match– performs an $elemMatch so you can match an entire document within an array
正则运算符
MongoDB使用Perl兼容正则表达式编译,对正则表达式提供了全面的支持。
$regex$options
其他运算符
$mod[(quotient), (result)]——value % x == y, wherexandyare two provided values$type—— 如果元素的类型符合指定的BSON类型则匹配text—— 如果在建立文本索引的字段执行文本搜索
列表字段查询
# find all pages whose first tag was db
age.objects(tags__0='db')
# The string queries operators can be used as well for querying a list field
Page.objects(tags__iexact='db')
# comments - skip 5, limit 10
Page.objects.fields(slice__comments=[5, 10])
# For updating documents, if you don’t know the position in a list, you can use the $ positional operator
Post.objects(comments__by="joe").update(**{'inc__comments__$__votes': 1})
mongoengine提供了mongosh语句作为查询参数,可以直接集成到查询中。
TEST.objects(__raw__={'stage_result': 'Passed'})
mongsh允许使用正则表达式查询:
// 查询由`Ba`开头的用户姓
db.Users.find({'last_name': /^Ba/})
忽略、限制、排序和映射
$slice 选择返回文档的子集
mongosh提供了skip和limit选项,我们可以使用这些选项进行分页查询和现实评论文档。
db.table_catalogue.find({stage_result: 'Passed'}).skip(0).limit(10)
如果要对查询结果进行排序。
db.table_catalogue.find({stage_result: 'Passed'}).skip(0).limit(10).sort('BUILD_ID': -1)