MongoDB : How to multiply a field that appears only in $project?

≡放荡痞女 提交于 2020-01-21 19:13:10

问题


I'm joining ($lookup) two collection the following way :

  const LEAD_PRICE  = ....; // doesn't matter 
  Client.aggregate(
      [
        {
          $lookup: {
            from: "clientboughtleads",
            localField: "_id",
            foreignField: "Client",
            as: "ClientLeads"
          }
        },

        {
          $project: {
            ClientId: "$_id",
            RegistrationDate: "$date",
            TotalPurchasedLeads: {
              $size: "$ClientLeads"
            },
            IncomeFromClient: {     // This one is always undefined
              $multiply: [LEAD_PRICE / 2, "$TotalPurchasedLeads"]
            }
          }
        }
      ]

I want to calculate IncomeFromClient by the mul of a const and a field that is been also calculated - TotalPurchasedLeads , however it returns NULL :

 [
[0]   {
[0]     _id: 5e0e43ae82a71e0017dccb20,
[0]     ClientId: 5e0e43ae82a71e0017dccb20,
[0]     RegistrationDate: 2020-01-02T21:25:34.000Z,
[0]     TotalPurchasedLeads: 4,
[0]     IncomeFromClient: null      // This one is not calculated 
[0]   }
[0] ]

How can I get the size of the $lookup collection when calculating a field that is being $projected ?


回答1:


Please use addFields keyword after we can use key in project .

 const LEAD_PRICE  = ....; // doesn't matter 
  Client.aggregate(
      [
        {
          $lookup: {
            from: "clientboughtleads",
            localField: "_id",
            foreignField: "Client",
            as: "ClientLeads"
          }
        },
   {
     $addFields: {
       TotalPurchasedLeads: {
              $size: "$ClientLeads"
          }
     }
   },
        {
          $project: {
            ClientId: "$_id",
            RegistrationDate: "$date",
            TotalPurchasedLeads:1,
            IncomeFromClient: {     // This one is always undefined
              $multiply: [LEAD_PRICE / 2, "$TotalPurchasedLeads"]
            }
          }
        }
      ]



回答2:


You cannot use the $projected value in the same $projection stage. So instead use its value

{
  "$project": {
    "ClientId": "$_id",
    "RegistrationDate": "$date",
    "TotalPurchasedLeads": {
      "$size": "$ClientLeads"
    },
    "IncomeFromClient": {
      "$multiply": [LEAD_PRICE / 2, { "$size": "$ClientLeads" }]
    }
  }
}


来源:https://stackoverflow.com/questions/59576585/mongodb-how-to-multiply-a-field-that-appears-only-in-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!