2016-02-29 45 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是數組中平展值的數量。