繁体   English   中英

使用 $lookup 获取子文档

[英]Getting subdocuments using $lookup

我想使用 $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 数组...

您可以在 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"
  }}
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM