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)