2016-11-25 37 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" 
      } 
     } 
    } 
}