如何在多个条件下对 MongoDB collection 中所有文档的键值求和

How to sum the value of a key across all documents in a MongoDB collection with multiple conditions

我正在尝试使用用户 ID 和服务状态来总结用户已完成的服务总量。我的 collection 看起来像这样:

[
  {
    _id: '5543333',
    title: 'service 1',
    description: 'des 1',
    status: 'completed',
    amount: 3000,
    user_id: '1',
  },
  {
    _id: '5543563',
    title: 'service 2',
    description: 'des 2',
    status: 'in progress',
    amount: 5000,
    user_id: '1',
  },
  {
    _id: '5542933',
    title: 'service 3',
    description: 'des 3',
    status: 'completed',
    amount: 4000,
    user_id: '1',
  },
];

预期结果:[{total: 7000}]

我尝试过的:

db.services.aggregate([
        {
          $group: {
            _id: '',
            price: {
              $sum: {
                $cond: [
                  {
                    $and: [
                      { $eq: ['$status', 'completed'] },
                      { $eq: ['$user_id', user.id] },
                    ],
                  },
                  '$price',
                  0,
                ],
              },
            },
          },
        },
        {
          $project: {
            _id: 0,
            total: '$price',
          },
        },
      ]);
  
  

我得到的结果:[{total: 0}]

我的观察:它适用于单一条件,但不适用于多个条件。

您可以先按状态筛选,然后按user_id分组。

工作playground

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$eq": [
          "$status",
          "completed"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": "$user_id",
      "total": {
        "$sum": "$amount"
      }
    }
  }
])