将三种不同的聚合物合并为一种

时间:2015-11-22 11:07:39

标签: mongodb python-3.x pymongo

我有三种不同的聚合,我想将它们合并为一种。

objsCount = self.db.bidding.aggregate([
  { "$group": {
      "_id": "$bid_item",
      "number_of_objects": { "$sum": 1 }
  }}
])

objsPrice = self.db.bidding.aggregate([
  {"$match": {"$and" : [{"price": {"$ne":"null"}},{"users":{"$ne":"null"}}]}},
  { "$group": {
      "_id": "$bid_item",
      "total_price": { "$sum": '$price' },
      "total_users": { "$sum": '$users' }
  }}
])

objsHigestBid = self.db.bidding.aggregate([
  {"$match": {"$and" : [{"highestBid": {"$ne":"null"}},{"users":{"$ne":"null"}}]}},
  { "$group": {
      "_id": "$bid_item",
      "total_number_of_users_after_bid": { "$sum": '$highestBid' }
  }}
])

我正在寻找的输出是:

 [{ _id : '',
  number_of_objects : '',
  total_price : '', 
  total_users : '', 
  total_number_of_users_after_bid : ''
 },...]

如何将我的“聚合”更改为一个可以实现此目标的“聚合”?

1 个答案:

答案 0 :(得分:0)

使用单个 $group 管道,您可以利用管道步骤中的 $cond 运算符来评估基于指定的逻辑,如下所示:

db.bidding.aggregate([    
    { 
        "$group": { 
            "_id": "$bid_item",             
            "number_of_objects": { "$sum": 1 },
            "total_price": {
                "$sum": {
                    "$cond": [ { "$ne": [ "$price", "null" ] }, "$price", 0 ]
                }
            },
            "total_users": {
                "$sum": {
                    "$cond": [ { "$ne": [ "$users", "null" ] }, "$users", 0 ]
                }
            },
            "total_number_of_users_after_bid": {
                "$sum": {
                    "$cond": [ 
                        {
                            "$and": [
                                { "$ne": [ "$highestBid", "null" ] },
                                { "$ne": [ "$users", "null" ] }
                            ]
                        },
                        "$highestBid", 0 
                    ]
                }
            } 
        }  
    }
])