2016-11-25 73 views
0

(蒙戈新手在這裏,不好意思)我有一個MongoDB的集合,這個模式映射縮減的結果:排序匹配組由ID合計

{ 
    "_id" : "John Snow", 
    "value" : { 
    "countTot" : 500, 
    "countCall" : 30, 
    "comment" : [ 
     { 
     "text" : "this is a text", 
     "date" : 2016-11-17 00:00:00.000Z, 
     "type" : "call" 
     }, 
     { 
     "text" : "this is a text", 
     "date" : 2016-11-12 00:00:00.000Z, 
     "type" : "visit" 
     }, 
     ... 
    ] 
    } 
} 

我的目標是有包含所有意見的文件某種類型的。例如,與所有的電話約翰雪文件。

我管理使用此有某種類型的所有註釋:

db.general_stats.aggregate(

    { $unwind: '$value.comment' }, 

    { $match: { 
     'value.comment.type': 'call' 
    }} 
) 

但是,我無法找到一個方法來組由ID(例如約翰·斯諾)接收到的數據,甚至使用$組屬性。任何想法 ?

感謝您的閱讀。

回答

1

這裏是爲您的查詢的解決方案。

db.getCollection('calls').aggregate([ 
    { $unwind: '$value.comment' }, 
    { $match: { 
     'value.comment.type': 'call' 
    }}, 
    { 
     $group : { 
      _id : "$_id", 
      comment : { $push : "$value.comment"}, 
      countTot : {$first : "$value.countTot"}, 
      countCall : {$first : "$value.countCall"}, 
     } 
    }, 
    { 
     $project : { 
      _id : 1, 
      value : {"countTot":"$countTot","countCall":"$countCall","comment":"$comment"} 
     } 
    } 
]) 

或要麼你可以去$項目$過濾選項

db.getCollection('calls').aggregate([ 
    { 
     $project: { 
     "value.comment": { 
      $filter: { 
       input: "$value.comment", 
       as: "comment", 
       cond: { $eq: [ "$$comment.type", 'call' ] } 
      } 
     }, 
     "value.countTot":"$value.countTot", 
     "value.countCall":"$value.countCall", 
     } 
    } 
]) 

在這兩種情況下,下面是我的輸出。

{ 
    "_id" : "John Snow", 
    "value" : { 
     "countTot" : 500, 
     "countCall" : 30, 
     "comment" : [ 
      { 
       "text" : "this is a text", 
       "date" : "2016-11-17 00:00:00.000Z", 
       "type" : "call" 
      }, 
      { 
       "text" : "this is a text 2", 
       "date" : "2016-11-17 00:00:00.000Z", 
       "type" : "call" 
      } 
     ] 
    } 
} 
0

下面是查詢,它是OP中存在的查詢的擴展。

db.general_stats.aggregate(
    { $unwind: '$value.comment' }, 
    { $match: { 
     'value.comment.type': 'call' 
    }}, 
    {$group : {_id : "$_id", allValues : {"$push" : "$$ROOT"}}}, 
    {$project : {"allValues" : 1, _id : 0} }, 
    {$unwind : "$allValues" } 
); 

輸出: -

{ 
    "allValues" : { 
     "_id" : "John Snow", 
     "value" : { 
      "countTot" : 500, 
      "countCall" : 30, 
      "comment" : { 
       "text" : "this is a text", 
       "date" : ISODate("2016-11-25T10:46:49.258Z"), 
       "type" : "call" 
      } 
     } 
    } 
}