MongoDB:如何将仅出现在 $project 中的字段相乘?

Posted

技术标签:

【中文标题】MongoDB:如何将仅出现在 $project 中的字段相乘?【英文标题】:MongoDB : How to multiply a field that appears only in $project? 【发布时间】:2020-04-21 21:36:31 【问题描述】:

我正在通过以下方式加入($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"]
            
          
        
      ]

我想通过一个 const 的 mul 和一个也被计算的字段来计算 IncomeFromClient - 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 集合的大小?

【问题讨论】:

您在进行投影之前尝试过$addFields 吗? docs.mongodb.com/manual/reference/operator/aggregation/… 【参考方案1】:

您不能在同一 $projection 阶段使用 $projected 值。所以改为使用它的值


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

【讨论】:

你太棒了!【参考方案2】:

我们可以在项目中使用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"]
            
          
        
      ]

【讨论】:

这太棒了,使用addFields!谢谢

以上是关于MongoDB:如何将仅出现在 $project 中的字段相乘?的主要内容,如果未能解决你的问题,请参考以下文章

如何 $project ObjectId 到 mongodb 聚合中的字符串值?

MongoDB Aggregate $project中,如果想新加一列常数,如何写?

求助啊,tp下,mongodb如何查询后只返回某个字段值

如何通过 $project 中提供的 _id 与 mongodb 聚合进行 $match?

MongoDB:从 Projection 中删除重复记录

mongodb备份还原