MongoDB聚合组_id由不同的字段组成

时间:2016-04-22 13:44:46

标签: mongodb aggregation-framework database nosql

我有收藏帐户:

{
  "_id": ObjectId("571a0e145d29024733793cfe"),
  "name": "Cash",
  "user": ObjectId("571a0e145d29024733793cfc")
}

和交易。交易可以有不同的字段:

{
  "_id": ObjectId("571a0e145d29024733793d06"),
  "amount": 100,
  "type": "earned",
  "account": ObjectId("571a0e145d29024733793cfe"),
  "user": ObjectId("571a0e145d29024733793cfc"),

},
{
  "_id": ObjectId("571a0e145d29024733793d04"),
  "amount": 300,
  "type": "spent",
  "account": ObjectId("571a0e145d29024733793cfe"),
  "user": ObjectId("571a0e145d29024733793cfc")
},
{
  "_id": ObjectId("571a0e145d29024733793d07"),
  "amount": 100,
  "type": "transfer",
  "sourceAccount": ObjectId("571a0e145d29024733793cfd"),
  "destinationAccount": ObjectId("571a0e145d29024733793cfe"),
  "user": ObjectId("571a0e145d29024733793cfc"),
}

我想为每个帐户创建一个统计小组。 我写了一个聚合框架查询到数据库:

db.transactions.aggregate([

  { $match: { user: user._id } },

  {
    $group: {
      _id: '$account',

      earned: {
        $sum: {
          $cond: [{ $eq: ['$type', 'earned'] }, '$amount', 0]
        }
      },

      spent: {
        $sum: {
          $cond: [{ $eq: ['$type', 'spent'] }, '$amount', 0]
        }
      },

      deposits: {
        $sum: {
          $cond: [{ $eq: ['$type', 'transfer'] }, '$amount', 0]
        }
      },

      withdrawal: {
        $sum: {
          $cond: [{ $eq: ['$type', 'transfer'] }, '$amount', 0]
        }
      },

      maxEarned: {
        $max: {
          $cond: [{ $eq: ['$type', 'earned'] }, '$amount', 0]
        }
      },

      maxSpent: {
        $max: {
          $cond: [{ $eq: ['$type', 'spent'] }, '$amount', 0]
        }
      },

      count: { $sum: 1 }

    }
  }
]);

但它无法正常工作。它仅适用于具有字段帐户的交易。 我想按字段帐户或sourceAccount或destinationAccount分组。

我也试过写在“_id”字段中:

_id: { account: '$account', sourceAccount: '$sourceAccount', destinationAccount: '$destinationAccount' }

_id: {$or: ['$account', '$sourceAccount', '$destinationAccount']}

_id: {$in: ['$account', '$sourceAccount', '$destinationAccount']}

但它会造成错误的群体或不起作用。

如何从不同的领域进行分组?

1 个答案:

答案 0 :(得分:1)

使用 $cond 运算符作为_id表达式,根据您指定的条件按键评估组。 $cond 运算符使用比较运算符 $gt 来计算布尔表达式,该表达式确定字段是否存在并使用此 {{3 }} 即可。因此,您可以重构您的管道,如下例所示:

db.transactions.aggregate([
    {
        "$group": {
            "_id": { 
                "$cond": [
                    { "$gt": [ "$account", null ] }, 
                    "$account", 
                    { 
                        "$cond": [
                            { "$gt": [ "$sourceAccount", null ] }, 
                            "$sourceAccount", 
                            "$destinationAccount" 
                        ] 
                    } 
                ] 
            },
            "count": { "$sum": 1 }
        }
    }
])

示例输出

{ "_id" : ObjectId("571a0e145d29024733793cfd"), "count" : 1 }
{ "_id" : ObjectId("571a0e145d29024733793cfe"), "count" : 2 }
相关问题