【问题标题】:How can I get top n buckets for an aggregation and all other buckets combined into an "other" bucket?如何获得聚合的前 n 个存储桶,以及将所有其他存储桶组合成一个“其他”存储桶?
【发布时间】:2016-04-15 08:54:09
【问题描述】:

假设一个集合的模式如下所示:

{
    "customer" : <unique-id-for-customer>,
    "purchase" : <number>,
}

现在,我想获得前 5 位客户(按购买数量),第 6 个桶是“其他”,它结合了其他客户的所有购买数量。

基本上,聚合的输出应该是这样的:

{ "_id" : "customer100", "purchasequantity" : 4000000 }
{ "_id" : "customer5", "purchasequantity" : 81800 }
{ "_id" : "customer4", "purchasequantity" : 40900 }
{ "_id" : "customer3", "purchasequantity" : 440 }
{ "_id" : "customer1", "purchasequantity" : 300 }
{"_id" : "others", "purchasequantity" : 29999}

【问题讨论】:

  • 我认为仅使用一个聚合命令是不可能的。
  • 我也尽了最大的努力.. 无法找到一种方法来在单个命令中检索结果。 db.aggregations.aggregate([{$sort:{purchasequantity:-1}},{$limit:5}]);和 db.aggregations.aggregate([{$sort:{purchasequantity:-1}},{$skip:5},{$group:{_id:'others',totalAmount:{$sum:'$purchasequantity'}} }]);结果必须合并。
  • 第一次聚合:db.test.aggregate([ { "$sort" : {"purchase" : -1} }, { "$project" : { _id : '$customer', 'purchase ' : 1 } }, { $limit : 5 } ]) 第二次聚合: db.test.aggregate([ { "$sort" : {"purchase" : -1} }, { $skip : 5 }, { "$组”:{_id:“其他”,“购买”:{$sum:“$purchase”}}}])

标签: mongodb mongodb-query pymongo aggregation-framework


【解决方案1】:

你想要的是weighting。为此,您需要通过$projecting 并使用$cond 运算符为您的文档添加权重,然后按“权重”按升序排序,按“购买数量”按降序排序。

db.collection.aggregate([
    { "$project": { 
        "purchasequantity": 1, 
        "w": { 
            "$cond": [ { "$eq": [ "$_id", "others" ] }, 1, 0 ] 
        } 
    }}, 
    { "$sort": { "w": 1, "purchasequantity": -1 } } 
])

返回:

{ "_id" : "customer100", "purchasequantity" : 4000000, "w" : 0 }
{ "_id" : "customer5", "purchasequantity" : 81800, "w" : 0 }
{ "_id" : "customer4", "purchasequantity" : 40900, "w" : 0 }
{ "_id" : "customer3", "purchasequantity" : 440, "w" : 0 }
{ "_id" : "customer1", "purchasequantity" : 300, "w" : 0 }
{ "_id" : "others", "purchasequantity" : 29999, "w" : 1 }

【讨论】:

  • 这似乎不起作用。它返回所有具有“w”0 和字段“_id”作为 ObjectID 的元素。还有,如何限制桶的数量?
猜你喜欢
  • 2019-10-31
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多