2016-02-29 92 views
0

从每个记录阵列独特的价值观我有MongoDB的集合,它看起来像这样:获取MongoDB中

{ 
    "_id" : ObjectId("56d3e53b965b57e4d1eb3e71"), 
    "name" : "John", 
    "posts" : [ 
       { 
        "topic" : "Harry Potter", 
        "obj_ids" : [ 
          "1234" 
        ], 
        "dates_posted" : [ 
          "2014-12-24" 
        ] 
       }, 
       { 
        "topic" : "Daniel Radcliffe", 
        "obj_ids" : [ 
          "1235", 
          "1236", 
          "1237" 
        ], 
        "dates_posted" : [ 
          "2014-12-22", 
          "2015-01-13", 
          "2014-12-24" 
        ] 
       } 
       ], 
}, 
{ 
    "_id" : ObjectId("56d3e53b965b57e4d1eb3e72"), 
    "name" : "Jane", 
    "posts" : [ 
       { 
        "topic" : "Eragon", 
        "tweet_ids" : [ 
          "1672", 
          "1673", 
          "1674" 
        ], 
        "dates_posted" : [ 
          "2014-12-27", 
          "2014-11-16" 
        ] 
       } 
      ], 
} 

我怎么能查询到得到这样一个结果:

{ 
     "name": "John", 
     "dates": ["2014-12-24", "2014-12-22", "2015-01-13"] 
}, 
{ 
     "name": "Jane", 
     "dates" : ["2014-12-27", "2014-11-16"] 
} 

我需要的日期是唯一的,因为“2014-12-24”出现在"posts"的两个元素中,但我只需要一个。

我想这样做db.collection.aggregate([{$unwind: "$posts"}, {$group:{_id:"$posts.dates_posted"}}])这给了我的结果是这样的:

{ "_id" : [ "2014-12-24", "2014-12-22", "2015-01-13", "2014-12-24" ] } 
{ "_id" : [ "2014-12-27", "2014-11-16" ] } 

我如何删除重复项,还可以获得对应日期的名字吗?

回答

1

您将需要使用$addToSet运算符来维护唯一值。其中一种方法是:

  • unwind的帖子。
  • unwind“posts.date_posted”,以便数组变平,并且可以在小组阶段中汇总该值。
  • 然后group_id和积累日期字段的唯一值,以及name

代码:

db.collection.aggregate([ 
{ 
    $unwind:"$posts" 
}, 
{ 
    $unwind:"$posts.dates_posted" 
}, 
{ 
    $group: 
     { 
      "_id":"$_id", 
      "dates":{$addToSet:"$posts.dates_posted"}, 
      "name":{$first:"$name"} 
     } 
}, 
{ 
    $project: 
      { 
       "name":1, 
       "dates":1, 
       "_id":0 
      } 
} 
]) 

这种方法在于的缺点,它使用两个unwind阶段,这是宁静的成本,因为它会增加文件至后级的数量,输入,由乘数为n,其中n是数组中平展值的数量。