我想使用$ lookup从另一个集合中获取子文档,但是它不起作用。目前脑死了...
我有一个交易集合
示例交易
{
type: 'PURCHASE', // but it can be something else also eg ORDER
reference: '11', // String
amount: 50,
date: 2018-07-18T10:00:00.000Z
}
我有一个采购集合
{
code: 11 // Integer
name: 'Product X',
amount: 50
}
我的汇总如下
Purchase.aggregate([
{
$lookup:
{
from: "transactions",
let: { code: '$code' },
pipeline: [
{
},
{
$match: { $expr:
{ $and:
[
{ $eq: [ "$reference", "$$code" ] },
{ $eq: [ "$type", "PURCHASE" ] }
]
}
}
}
],
as: "transactions",
}
}
]);
结果是一个空的tarnsactions数组...
答案 0 :(得分:2)
您可以尝试在mongodb 3.6 中进行以下汇总。只需使用$toLower
聚合将code
类型从整数更改为字符串,或者可以在mongodb 4.0
$toString
Purchase.aggregate([
{ "$lookup": {
"from": "transactions",
"let": { "code": { "$toLower": "$code" } },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$reference", "$$code" ] },
"type": "PURCHASE"
}}
],
"as": "transactions"
}}
])