2016-01-21 141 views
0

我在下面的mongodb數據中遇到了問題。 我想獲得數據[projects][log][subject]。 所以,我想這樣的選擇數組內部元素

$project':{_id:0, projects.log.subject:1} 

,但它是不正確的語法..

{ 
    "_id": ObjectID("569f3a3e9d2540764d8bde59"), 
    "A": "book", 
    "server": "us", 
    "projects": [ 
     { 
      "domainArray": [ 
       { 
        ~~~~ 
       } 
      ], 
      "log": [ 
       { 
        ~~~~~, 
        "subject": "I WANT THIS" 
       } 
      ], 
      "before": "234234234" 
     }, 
     { 
      "domainArray": [ 
       { 
        ~~~~ 
       } 
      ], 
      "log": [ 
       { 
        ~~~~~, 
        "subject": "I WANT THIS" 
       } 
      ], 
      "before": "234234234" 
     },.... 
    ] //end of projects 
}//end of document 

我怎樣才能通過[subject]得到的數據組?我不知道這個想法..

Edited- 我預計這樣的

{ 
"subject":"first", 
"subject":"second", 
"subject":"third", 
"subject":"~~~" 
} 

是否有可能數據?我只想獲得一些主題。

+0

您可以編輯您的問題,以顯示預期的輸出? – chridam

+0

將'projects.log.subject'包裹在引號中。 –

+0

您能否請嘗試發佈預期結果的有效文檔? – styvane

回答

0

不確定這是否是您的預期結果。能否請您試試這個:

db.project.aggregate([ 
      {$project:{projects:1,_id:0}}, 
      {$unwind:"$projects"}, 
      {$unwind:"$projects.log"}, 
      {$project:{subject:"$projects.log.subject",_id:0}} 
      ]) 

和地圖,減少對字數的上述結果如下:

//map function 
var map = function() { 

    for(var i in this.projects) 
    { 
     for(var j in this.projects[i].log) 
     { 

     var arrayWords = this.projects[i].log[j].subject.split(" "); 
     for(var k = 0; k < arrayWords.length; k++) 
     { 
      emit(arrayWords[k],{occurance:1}); 
     } 

     } 

    } 

}; 

//reduce function 
function reduce(word, arrayOccurance) { 

    var totalOccurance = 0; 

    for (var i = 0; i < arrayOccurance.length; i++) 
    { 
    totalOccurance = totalOccurance + arrayOccurance[i].occurance; 
    } 

    return { occurance:totalOccurance }; 
} 

//combine both function into operation and output result into wordOccurance collection 

db.project.mapReduce(
         map, 
         reduce, 
         { 
          query: {"projects.log.subject":"~~~~~"}, 
          out: "wordOccurance" 
         } 
        ) 

//query the result output 

db.wordOccurance.find() 

你可以改變下映射縮減查詢到你的主題是想字數匹配。請讓我知道如果我的mapreduce函數不符合您的預期結果。

您也可以參考以下兩個頁面來創建和解決Map和Reduce函數:

Troubleshoot the Map Function

Troubleshoot the Reduce Function

+0

感謝它對我來說是完美的。非常感謝你,我想要那個數據 – Acool5

+0

而且.. HaRLoFei,你可以讓我知道如何使用mapreduce使用上面的結果。 我想統計主題中的「單詞」:「~~~~~」。我剛剛搜索地圖減少。它適合用於計算單詞 – Acool5

+0

Hi @ Acool5我已添加mapreduce。不確定它是否符合您的預期結果,如果不符合,請張貼您的預期結果。 – HaRLoFei