【问题标题】:Mongo - Aggregate Group Lookup ValuesMongo - 聚合组查找值
【发布时间】:2020-08-21 21:57:41
【问题描述】:

我正在尝试总结查找中列出的值。我有 2 个收藏:

订阅(伪代码)

{
   _id,
   purchaseDate: Date,
   wholesalePrice: Number,
   purchasePrice: Number,
   retailPrice: Number,
   userID: String,
}

付款

{
   _id,
   statementMonth: String, // e.g. 2020-08 (same as grouped id in Subscriptions)
   paymentDate: Date,
   userID: String,
   amountPaid
}

用户需要在月底转移利润率值。因此,我想为 Statements 创建一个输出。这些将所有订阅和付款分组到每月记录中,其中包含所有数据的摘要。我已经设法创建了第一组的所有内容,但是一旦我进行查找以获取付款详细信息,一切似乎都失败了。

这是我目前的管道

    {
        "$match": {
            "userID": [provided UserID]
        }
    }, 
    {
        "$group": {
            "_id": {
                "$dateToString": {
                    "format": "%Y-%m",
                    "date": "$purchaseDate"
                }
            },
            "totalWholesalePrice": {
                "$sum": "$wholesalePrice"
            },
            "totalPurchasePrice": {
                "$sum": "$purchasePrice"
            },
            "count": {
                "$sum": 1.0
            }
        }
    }, 
    {
        "$addFields": {
            "totalAmountDue": {
                "$subtract": [
                    "$totalPurchasePrice",
                    "$totalWholesalePrice"
                ]
            }
        }
    }, 
    {
        "$lookup": {
            "from": "transactions",
            "localField": "_id",
            "foreignField": "statementMonth",
            "as": "transactions"
        }
    }, 
    {
        "$unwind": {
            "path": "$transactions",
            "preserveNullAndEmptyArrays": true
        }
    }, 
    {
        "$sort": {
            "_id": -1.0
        }
    }

如果有 2 笔交易,则返回 2 条记录:

{ 
    "_id" : "2020-08", 
    "totalWholesalePrice" : NumberInt(89), 
    "totalPurchasePrice" : 135.55, 
    "count" : 8.0, 
    "totalAmountDue" : 46.55, 
    "transactions" : {
        "_id" : ObjectId("5f3faf2216d7a517bc51bfae"), 
        "date" : ISODate("2020-04-20T11:23:40.284+0000"), 
        "statementMonth" : "2020-08", 
        "merchant" : "M1268360", 
        "amountPaid" : "40"
    }   
}

{ 
    "_id" : "2020-08", 
    "totalWholesalePrice" : NumberInt(89), 
    "totalPurchasePrice" : 135.55, 
    "count" : 8.0, 
    "totalAmountDue" : 46.55, 
    "transactions" : {
        "_id" : ObjectId("5f3fc13f16d7a517bc51c047"), 
        "date" : ISODate("2020-04-20T11:23:40.284+0000"), 
        "statementMonth" : "2020-08", 
        "merchant" : "M1268360", 
        "amountPaid" : "2"
    }
}

我希望最终的 JSON 是:

    { 
        "_id" : "2020-08", 
        "totalWholesalePrice" : NumberInt(89), 
        "totalPurchasePrice" : 135.55, 
        "count" : 8.0, 
        "totalAmountDue" : 46.55, 
        "transactions" : [{
            "_id" : ObjectId("5f3faf2216d7a517bc51bfae"), 
            "date" : ISODate("2020-04-20T11:23:40.284+0000"), 
            "statementMonth" : "2020-08", 
            "merchant" : "M1268360", 
            "amountPaid" : "40"
        } 
        {
            "_id" : ObjectId("5f3fc13f16d7a517bc51c047"), 
            "date" : ISODate("2020-04-20T11:23:40.284+0000"), 
            "statementMonth" : "2020-08", 
            "merchant" : "M1268360", 
            "amountPaid" : "2"
        }],
        "totalPaid" : 42, 
        "totalBalance" : 4.55, 
    }

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您需要再添加一个管道

    db.collection.aggregate([
      {
        $group: {
          "_id": "$id",
          "transactions": { //Grouping transactions together
            "$addToSet": "$transactions"
          },
          "totalWholesalePrice": {//As all values are unique getting the first
            "$first": "$totalWholesalePrice"
          }
          //Similarly add the needed fields - use $first, $addToSet
        }
      }
    ])
    

    playground

    获取总数:

    db.collection.aggregate([
      {
        $group: {
          "_id": "$id",
          "transactions": {
            "$addToSet": "$transactions"
          },
          "totalWholesalePrice": {
            "$first": "$totalWholesalePrice"
          },
          "totalAmountPaid": {
            $sum: {
              $toInt: "$transactions.amountPaid" //you stored as string, convert to appropriate type
            }
          }
        }
      }
    ])
    

    playground

    【讨论】:

    • 感谢 Gibbs,这有助于对交易进行分组,但是,我如何获得 amountPaid 的总和值?我试过:totalPaid: { $sum: "$transactions.amountPaid" }。应该是 42 但我得到 0
    • 吉普斯——你是枪!解决了我一整天都在尝试解决的问题。谢谢
    • 很高兴它有帮助。如果有帮助,您能否投票并接受答案:) +1 表示您的尝试和正确的问题
    • 接受了,不幸的是我的代表太低而无法投票。希望这可以帮助其他人,他们会投票
    • 没有问题继续摇摆:)
    猜你喜欢
    • 2020-08-26
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2019-05-06
    • 2021-10-02
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多