2015-01-12 84 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}}