【问题标题】:how to access field name in mongoose $aggregate->$lookup-> pipeline->$match如何访问 mongoose $aggregate->$lookup-> pipeline->$match 中的字段名称
【发布时间】:2019-11-07 23:48:08
【问题描述】:

我有以下代码。

Users.aggregate([{
     $lookup: {
          from: "payments",
          // localField:"_id",
          // foreignField:"restaurant_id",
          let: {
               id: "$_id"
          },
          pipeline: [
               {
                    $match: {
                         status: "Active", // If I add only this line it returns the result ->
                         restaurant_id:"$id" //or "$_id"  ->but after adding this line it return empty array
                         //if I change $id to static value of id result comes 
                    },
               }
          ],
          as: "subscription"
     }
}])

我无法在$match 中使用字段名称。如果我正在编写静态 id,它可以正常工作,但我需要使用动态 _id。请建议我如何在$match 中使用字段名称。我用过很多东西,比如$and$expr,但没有任何效果。

两个集合都在同一个数据库中

MongoDB服务器版本:3.6.9

“猫鼬”:“^5.3.4”

【问题讨论】:

    标签: node.js mongodb express mongoose aggregate


    【解决方案1】:

    我已经从这个参考Specify Multiple Join Conditions with $lookup解决了这个问题

    Users.aggregate([
         {
              $lookup: {
                   from: "payments",
                   // localField:"_id",
                   // foreignField:"restaurant_id",
                   let: {
                        id: "$_id" //localField
                   },
                   pipeline: [
                        {
                             $match: {
                                  $expr:{
                                       $and:[
                                            {$eq: ["$status","Active"]},
                                            {
                                                 $eq:[
                                                      "$$id", //localField variable it can be used only in $expr
                                                      "$restaurant_id" //foreignField 
                                                 ]
                                            }
                                       ]
                                  }
    
    
                             },
                        }
                   ],
                   as: "subscription"
              }
         }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 2021-11-17
      • 2016-11-26
      • 2019-05-07
      • 1970-01-01
      相关资源
      最近更新 更多