首页 > 解决方案 > MongoDB:如何将仅出现在 $project 中的字段相乘?

问题描述

我通过以下方式加入($lookup)两个集合:

  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"]
            }
          }
        }
      ]

我想IncomeFromClient通过 mul 的 const 和一个也被计算的字段来计算 - TotalPurchasedLeads,但是它返回 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] ]

在计算 $projected 的字段时,如何获取 $lookup 集合的大小?

标签: node.jsmongodbmongooseaggregation-frameworkmongoose-schema

解决方案


在我们可以在 project 中使用 key 之后,请使用 addFields 关键字。

 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"]
            }
          }
        }
      ]

推荐阅读