mongodb aggregate 联表 nest.js +monoose .js实现
需要连接外部表(集合),或者本表(集合)某些字段需要相互转化。
//mongodb 文档结构
{
"_id": {
"$oid": "65a0fe4f079597cfdb81e57c"
},
"token": "yPFas4nk8M1b",
"queueId": "65a0fe34079597cfdb81e578",
"queue": {
"sessionId": "65a0fe15079597cfdb81e575",
"session": {
"branchCode": "710849",
"branchIp": "127.0.0.1",
"nameEn": "dse",
"nameTc": "desf",
"nameSc": "234",
"onlineStart": "123",
"onlineEnd": "343",
"start": "1231",
"end": "3211",
"_id": {
"$oid": "65a0fe15079597cfdb81e575"
}
},
"pplFrom": 10,
"pplTo": 13,
"prefix": "zhongcai",
"_id": {
"$oid": "65a0fe34079597cfdb81e578"
}
},
"ticketNumber": "A22",
"type": 0,
"status": 0,
"ivrsStatus": 0,
"ivrsRetry": 0,
"blastStatus": 0,
"blastRetry": 0,
"apiVersion": 2,
"platform": 0,
"cancelRetry": 0,
"called": 0,
"createdAt": {
"$date": "2024-01-12T08:54:39.672Z"
},
"__v": 0
}
//mongodb 的aggregate 的聚合实现方式方式
// 注释的内容是采用的pineline 方式,可以实现更加复杂的逻辑,比如增加分组、多次match 等方式。
let aggregate=[
{
$lookup:{
from:'branch',//外部表、临时表的名称
// let :{branchCode:"$session.branchCode"},
localField:"session.branchCode",//xxxxModel映射表的代码的字段
foreignField:"branchCode",//branc表的字段
// let: { branchCode: "$session.branchCode"},
// pipeline: [ {
// $match: {
// $expr: {
// $and: [
// { $eq: [ "$$branchCode", "$branchCode" ] },
// ]
// }
// }
// } ],
as:'branch'//将连接的表输出为某字段
}
}]
this.xxxxModel.aggregate(aggregate)//xxxModel 是mongose module