MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

MongoDB:Como multiplicar um campo que aparece apenas em $project?


Por favor, use a palavra-chave addFields depois que pudermos usar a chave no projeto.
 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"]
            }
          }
        }
      ]