使用 $lookup 获取子文档
Getting subdocuments using $lookup
我想使用 $lookup 从另一个 collection 获取子文档,但它不起作用。目前脑死亡...
我有一个 collection 交易
示例交易
{
type: 'PURCHASE', // but it can be something else also eg ORDER
reference: '11', // String
amount: 50,
date: 2018-07-18T10:00:00.000Z
}
我有一个 collection 用于购买
{
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 数组...
您可以在 mongodb 3.6 中尝试以下聚合。只需使用 mongodb 4.0
中的 $toLower
aggregation or can use $toString
将 code
类型从整数更改为字符串
Purchase.aggregate([
{ "$lookup": {
"from": "transactions",
"let": { "code": { "$toLower": "$code" } },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$reference", "$$code" ] },
"type": "PURCHASE"
}}
],
"as": "transactions"
}}
])
我想使用 $lookup 从另一个 collection 获取子文档,但它不起作用。目前脑死亡...
我有一个 collection 交易
示例交易
{
type: 'PURCHASE', // but it can be something else also eg ORDER
reference: '11', // String
amount: 50,
date: 2018-07-18T10:00:00.000Z
}
我有一个 collection 用于购买
{
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 数组...
您可以在 mongodb 3.6 中尝试以下聚合。只需使用 mongodb 4.0
中的$toLower
aggregation or can use $toString
将 code
类型从整数更改为字符串
Purchase.aggregate([
{ "$lookup": {
"from": "transactions",
"let": { "code": { "$toLower": "$code" } },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$reference", "$$code" ] },
"type": "PURCHASE"
}}
],
"as": "transactions"
}}
])