如何在 Mongo 查询中使用总和进行聚合?

How to do aggregation with sum in a Mongo query?

我是 MongoDB 的新手,需要编写此查询。我的JSON请求是这样的。我需要使用聚合

在 mongodb 中构建查询

JSON

[
  {
    "_id": {
      "user_id": "1",
      "name": "Madhu",
      "LeadName": "Test",
      "status": "Lost",
      "lead_value": 78000
    }
  },
  {
    "_id": {
      "user_id": "1",
      "name": "Madhu",
      "LeadName": "Trail",
      "status": "Trial",
      "lead_value": 75200
    }
  },
  {
    "_id": {
      "user_id": "1",
      "name": "Madhu",
      "LeadName": "Teja",
      "status": "Customer",
      "lead_value": 45000
    }
  },
  {
    "_id": {
      "user_id": "1",
      "name": "Madhu",
      "LeadName": "Kushbu",
      "status": "Trial",
      "lead_value": 20000
    }
  },
  {
    "_id": {
      "user_id": "1",
      "name": "Madhu",
      "LeadName": "Krishna",
      "status": "Trial",
      "lead_value": 18000
    }
  },
  {
    "_id": {
      "user_id": "1",
      "name": "Madhu",
      "LeadName": "Test1",
      "status": "Trial",
      "lead_value": 12000
    }
  },
  {
    "_id": {
      "user_id": "89",
      "name": "Prashanth Reddy",
      "LeadName": "Ganesh",
      "status": "Trial",
      "lead_value": 12000
    }
  },
  {
    "_id": {
      "user_id": "89",
      "name": "Prashanth Reddy",
      "LeadName": "Hima Sree",
      "status": "Customer",
      "lead_value": 1750
    }
  }
]

我想要像除 "Customer" 之外的所有 "Lead_values" 之和的响应,并且还要计算状态

[
  {
    "_id": {
      "user_id": "1",
      "name": "Madhu",
      "lead_value": 120354,
      "count" : 5
    }
  },
  {
    "_id": {
      "user_id": "89",
      "name": "Prashanth Reddy",
      "lead_value": 12000,
      "count" : 1
    }
  }
]

如何在MongoDB聚合中写入?

你只需要一个简单的$group阶段:

db.collection.aggregate([
    {
        $match: {
            "_id.status": {$ne: "Customer"}
        }
    },
    {
        $group: {
            _id: "$_id.user_id",
            lead_values: {$sum: "$_id.lead_value"},
            name: {$first: "$_id.name"},
            count: {$sum: 1}
        }
    }
])

您现在可以根据需要重新格式化数据。

您可以使用此查询,以获得完美的结果。 在这里。

db.getCollection('YOUR_COLLECTION').aggregate([
    {
        $match: {
            "_id.status": {$ne: "Customer"}
        }
    },
    {
        $group: {
            _id: "$_id.user_id",
            lead_values: {$sum: "$_id.lead_value"},
            name: {$first: "$_id.name"},
            count: {$sum: 1}
        }
    }
])

在这里你可以看到,我们如何使用$sum with $group