MongoDB 学习笔记
目前已见的操作符
聚合操作符
$match
用于过滤数据,只输出符合条件的文档。
$match使用MongoDB的标准查询操作
$sort
将输入文档排序后输出
{'$match': {'birthday': {'$gt': birthday_start}}}
{'$match': {'birthday': {'$lt': birthday_end}}}
{'$match': {'age': {'$gte': age_list[0]}}}
{'$match': {'year': year}}
{'$match': {'user_id': int(user_id)}}
{'$sort': {sorts.replace('-', ''): -1}}$skip
在聚合管道中跳过指定数量的文档,并返回余下的文档。
$limit
用来限制MongoDB聚合管道返回的文档数。
$project
修改输入文档的结构。
可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。
其中可以将0/1视为布尔显示的设置
{'$skip': (page - 1) * page_size},
{'$limit': page_size},
{'$project':
{
'_id': 0,
'user_id': 1,
'company': 1,
'name': 1,
'gender': 1,
'birthday': 1,
'last_check_time': 1,
'last_check_score': 1
}
}$group
将集合中的文档分组,可用于统计结果。
$min
$max
获取集合中所有文档对应值得最小/大值。
{'$group': {'_id': 'null',
'min': {'$min': '$last_check_score'},
'max': {'$max': '$last_check_score'}}},
{'$project': {'_id': 0, 'min': 1, 'max': 1}}]$unwind
Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.
从含有数组的输入文档解构并输出文档中的每个元素,每个输出文件含有输入文档中被元素替换数组的值。
输入文档中若有数组,其中的值会解构为元素并被替换掉,然后输出。
{'$unwind': '$tree_score.个体健康.children'},
{'$project': {'_id': 0,
'name': '$tree_score.个体健康.children.name',
'score': '$tree_score.个体健康.children.value',
'children': '$tree_score.个体健 康.children.children'}},
{'$project': {'children.children': 0}}]如果取出的文档的嵌套逻辑足够复杂,可以尝试多次使用$project来筛选文档的结果集,这样做亦可以提高查询效率

