Aggregate的 $lookup
和 $match
,可用于MangoDB的联表
直接上代码
两个表介绍
- services表
number: 服务号码
flow: 流程名称 - flows表
name: 流程名称
config: 流程配置
services表 和 flows 表,通过flow和name关联。
联表查询
想实现查询services表时,关联查询出引用的flow的详细配置,方便前台展示
用的aggrgete的Pipeline参数如下
[
{
'$lookup': {
'from': 'flows',
'localField': 'flow',
'foreignField': 'name',
'as': 'flow_detail'
}
}
]
带上过滤
想实现查询services表的指定service,关联查询出引用的flow的详细配置,方便前台展示
用的aggrgete的Pipeline参数如下
[
{
'$lookup': {
'from': 'flows',
'localField': 'flow',
'foreignField': 'name',
'as': 'flow_content'
}
}, {
'$match': {
'number': '6666'
}
}
]
基于egg-mongo-native编码
最后基于上述pipeline参数实现编码如下
let args = {
pipeline: [
{
'$lookup': {
'from': 'flows',
'localField': 'flow',
'foreignField': 'name',
'as': 'flow_content'
}
}, {
'$match': {
'number': '6666'
}
}
]
}
const result = await this.app.mongo.get('database').aggregate('services', args)
console.log(result)
网友评论