2017-01-16 72 views
1

我收藏的文件這樣如何扁平化子文檔中蒙戈DB

{ 
"_id" : ObjectId("587c8d0364b6e32706f7edef"), 
"first_name" : "John", 
"last_name" : "Doe", 
"password" : "aasdjsabb12213b21bbcghc1h2", 
"shift" : "A", 
"dept" : "Management" 
"Requests" : [ 
    { 
     "weekId" : 1, 
     "MO" : 1, 
     "TU" : 2, 
     "W" : 3, 
     "TH" : 9, 
     "FR" : 10, 
     "SA" : 6, 
     "SU" : 1 
    } 
    ] 
} 

我想導出我的查詢到CSV的結果和需要領域壓扁了這樣

{ 
"_id" : ObjectId("587c8d0364b6e32706f7edef"), 
"first_name" : "John", 
"last_name" : "Doe", 
"password" : "aasdjsabb12213b21bbcghc1h2", 
"shift" : "A", 
"dept" : "Management" 
"weekId" : 1, 
"MO" : 1, 
"TU" : 2, 
"W" : 3, 
"TH" : 9, 
"FR" : 10, 
"SA" : 6, 
"SU" : 1 

} 

我試圖使用聚合函數,但無濟於事。任何人都可以建議我如何做到這一點?

這是我工作的代碼,但我不認爲這是正確的方式

db.req.aggregate([{$unwind:'$Requests'},{$project: {first_name:1,last_name:1,dept:1,"WeekId":"$Requests.weekdId","Mon":"$Requests.MO","Tue":"$Requests.TU","Wed":"$Requests.W","Thu":"$Requests.TH","Fri":"$Requests.FR","Sat":"$Requests.SA","Sun":"$Requests.SU"}},{$out:"results"}]); 
+0

你能提供一個你已經嘗試過的代碼示例嗎?知道你從哪裏開始將幫助用戶提供更有意義的答案。 –

+0

什麼是您的MongoDB服務器版本? – chridam

回答

1

您可以彙總查詢做到這一點,但它不是很漂亮:

db.test.aggregate([ 
    {$unwind:"$Requests"}, 
    {$project: 
     {_id:1, 
      first_name:1, 
      last_name:1, 
      password:1, 
      shift:1, 
      dept:1, 
      weekId:"$Requests.weekId", 
      MO:"$Requests.MO", 
      TU:"$Requests.TU", 
      W:"$Requests.W", 
      TH:"$Requests.TH", 
      FR:"$Requests.FR", 
      SA:"$Requests.SA", 
      SU:"$Requests.SU"}}]) 
    .pretty() 

所以基本上展開Requests數組,然後投射出您想要生成的文檔。希望這是有道理的。

+0

我已經在使用這段代碼。我附上了這個問題。 –