[英]Getting subdocuments using $lookup
I want to get the subdocuments from another collection using $lookup but it doesn't work.我想使用 $lookup 从另一个集合中获取子文档,但它不起作用。 Currently brain dead...
目前脑死亡...
I have a collection for Transactions我有一个交易集合
example transaction示例交易
{
type: 'PURCHASE', // but it can be something else also eg ORDER
reference: '11', // String
amount: 50,
date: 2018-07-18T10:00:00.000Z
}
I have a collection for Purchases我有一个可供购买的收藏
{
code: 11 // Integer
name: 'Product X',
amount: 50
}
My aggregation is the following我的聚合如下
Purchase.aggregate([
{
$lookup:
{
from: "transactions",
let: { code: '$code' },
pipeline: [
{
},
{
$match: { $expr:
{ $and:
[
{ $eq: [ "$reference", "$$code" ] },
{ $eq: [ "$type", "PURCHASE" ] }
]
}
}
}
],
as: "transactions",
}
}
]);
The result is an empty tarnsactions array...结果是一个空的 tarnsactions 数组...
You can try below aggregation in mongodb 3.6 .您可以在 mongodb 3.6 中尝试以下聚合。 Just change
code
type from integer to string using $toLower
aggregation or can use $toString
in mongodb 4.0只需使用
$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"
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.