2015-01-12 88 views
0

我在蒙戈DB集合中的下列那种文档的做与蒙戈DB聚合框架之

{ _id:xx, 
    iddoc:yy, 
    type1:"sometype1", 
    type2:"sometype2", 
    date: 
    { 
     year:2015, 
     month:4, 
     day:29, 
     type:"day" 
    }, 
    count:23 
} 

我想满场数由iddoc所有文档分组做一个总和,其中:

  • 在[ “type1A”, “type1B”,...] TYPE1
  • ,其中2型在[ “type2A”, “type2B”,...]
  • date.year:2015年,
  • 个date.month:4,
  • date.type: “天”
  • date.day我想4和7

    之间

然后将这些资金进行排序。

我认为这可能很容易在mongo数据库聚合框架内完成,但我对它很陌生,并且希望能够入门。

回答

2

这是简单的做有aggregation pipeline

db.test.aggregate([ 
    // Filter the docs based on your criteria 
    {$match: { 
    type1: {$in: ['type1A', 'type1B']}, 
    type2: {$in: ['type2A', 'type2B']}, 
    'date.year': 2015, 
    'date.month': 4, 
    'date.type': 'day', 
    'date.day': {$gte: 4, $lte: 7} 
    }}, 

    // Group by iddoc and count them 
    {$group: { 
    _id: '$iddoc', 
    sum: {$sum: 1} 
    }}, 

    // Sort by sum, descending 
    {$sort: {sum: -1}} 
]) 
+0

谢谢。是否有可能不仅通过iddoc进行分组,还通过type1进行分组?即一个多组由 – user2175783

+1

是的:'_id:{iddoc:'$ iddoc',type1:'$ type1'}' – JohnnyHK

+0

我怎么做一个多组通过对iddoc和type1说,鉴于文档与不同type1有计数字段命名不同?即如果type1是type1A,则计数字段将命名为counttype1A,如果type1是type1B,则计数字段将命名为counttype1B。我只想求和counttype1A,只计算1B型 – user2175783

1

如果我正确理解您:

db.col.aggregate 
(
    [{ 
    $match: 
    { 
     type1: {$in: ["type1A", type1B",...]}, 
     type2: {$in: ["type2A", type2B",...]}, 
     "date.year": 2015, 
     "date.month": 4,, 
     "date.day": {$gte: 4, $lte: 7}, 
     "date.type": "day" 
    } 
    }, 
    { 
    $group: 
    { 
     _id: "$iddoc", 
     total_count: {$sum: "$count"} 
    } 
    }, 
    { $sort: {total_count: 1}}] 
) 

这是过滤4和7(含)之间的场date.day(如果没有,使用$ gt和$ lt来排除它们)。它排序从低到高(上升)的结果,如果你想要做一个降序排序,则:

{$排序:{TOTAL_COUNT:-1}}