文章目录
Aggregation查询操作
筛选
{
$match: {
field1: "abc",
field2: { $gt: 3}
}
}
# 表示匹配出 1.字段field1的值为"abc" 且 2.字段field2的值大于3 的文档
条件操作符
$gt/$lt
大于/小于$gte/$lte
大等于/小等于$eq/$ne
等于/不等于$regex
正则匹配
联表
/**
* from: The target collection.
* localField: The local join field.
* foreignField: The target join field.
* as: The name for the results.
* pipeline: Optional pipeline to run on the foreign collection.
* let: Optional variables to use in the pipeline field stages.
*/
{
from: "schedule",
localField: "name",
foreignField: "schedule_name",
as: "schedule_info"
}
# 表示 以当前集合的所有文档,关联另一个集合
# from表示关联的集合名称
# localField/foreignField分别表示关联的两个集合所用的字段
# as表示关联上的文档要存在的数组的名称
展开
/**
* path: Path to the array field.
* includeArrayIndex: Optional name for index.
* preserveNullAndEmptyArrays: Optional
* toggle to unwind null and empty values.
*/
{
path: "$schedule_info"
}
# 表示把一个数组字段展开,
聚合管道 aggregation pipeline
通过聚合管道的方式串联起多个stage进行查询
stage
$match
{$match: <query> }
{$match: {$expr: { <aggregation expression> } } }
筛选出与query内容相匹配的文档
$group
{
$group:
{
_id: <expression>, // Group key,
<field1>: { <accumulator1> : <expression1> },
...
}
}
按照指定的_id
的取值分组,_id
可以使用字典来实现多个条件交叉下分组
$project
{ $project: { <specification(s)> } }
用来控制输出的文档要包含哪些字段
$lookup
{
$lookup:
{
from: <foreign collection>,
localField: <field from local collection's documents>,
foreignField: <field from foreign collection's documents>,
let: { <var_1>: <expression>, …, <var_n>: <expression> },
pipeline: [ <pipeline to run> ],
as: <output array field>
}
}
用来关联另一个集合实现"left outer join"的功能
from指定用来关联的集合
localField/foreignField分别指出关联的字段
let用来定义变量
pipeline可以在关联操作之前在被关联的集合上指定一些stage
as用来指定关联到的结果存放的字段名
$unwind
{
$unwind:
{
path: <field path>,
includeArrayIndex: <string>,
preserveNullAndEmptyArrays: <boolean>
}
}
将文档按照其中某个数组字段的每个元素,拆分成多个元素
path指定该数组字段
includeArrayIndex指定一个字段用来保存元素在原数组中的下标
preserveNullAndEmptyArrays表示是否保留空数组
accumulator
- addToSet: 对同一个group内取无序无重复集合
- push: 对同一个group内取顺序数组队列
优化
建立索引
mongodb支持在数组字段上建立索引