如何在猫鼬$ aggregate-> $ lookup->管道-> $ match

时间:2019-06-26 05:38:34

标签: node.js mongodb express mongoose aggregate

我有以下代码。

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”

1 个答案:

答案 0 :(得分: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"
          }
     }
])