【问题标题】:How to sum the value of a key across all documents in a MongoDB collection with multiple conditions如何对具有多个条件的 MongoDB 集合中的所有文档的键值求和
【发布时间】:2021-07-27 19:40:57
【问题描述】:

我正在尝试使用用户 ID 和服务状态来总结用户已完成的服务总量。我的收藏是这样的:

[
  {
    _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}]

我的观察:它适用于单个条件而不是多个条件。

【问题讨论】:

    标签: javascript node.js mongodb nosql aggregation-framework


    【解决方案1】:

    可以先按状态过滤,再按user_id分组。

    工作playground

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

    【讨论】:

    • 它仍然不起作用,复制粘贴您的解决方案,它返回一个空对象数组,其中 user_id 值为 NULL,总值为零
    • 它在操场上工作。检查操场。
    • 谢谢。只要我不使用引用另一个集合 id 的字段进行过滤,这就会起作用。如果我想使用引用的用户 ID 而不是状态进行过滤,该怎么办
    • 那你可以这样, "$match": { $expr: { "$eq": [ "$user_id", 1 ] } }
    猜你喜欢
    • 2011-06-05
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    相关资源
    最近更新 更多