2016-01-17 31 views
0
算常用詞

比方說,我有一些文件,MongoDB中與這些類型的信息的:的MongoDB - 2串

{ 
text: "this is the first this is" 
content: "this is this is" 
total: 0 
} 

我想指望有多少次在「文本」每個單詞appers「內容「,總結所有計數結果並放入」總計「字段。

在上面的例子: '這個' 在內容中出現兩次, '是'

:2 '的' 0 '第一':0, '這個':2, '是':2

總:2 + 2 + 0 + 0 + 2 + 2 = 8 所以我們希望把8場 '總'

我知道我應該通過遍歷集合這樣做(讓我們稱之爲'文件'):

db.documents.find().forEach(
    function(result) 
    { 
    ... 
    }) 

不是su重新把什麼放在裏面(我是新來的,和JS)

p.s:它應該區分大小寫。

回答

1

那麼,看看JS + MongoDB教程。您需要訪問MongoDB shell或MongoDB GUI(RoboMongo)才能執行。您可以創建一個新的函數,用於統計內容字段中的文本(通過您的規則)並將新字段添加到文檔中。

String.prototype.total = function(content) { 
    var result  = 0; 
    var contentArr = content.split(" "); 
    var textArr = this.split(" "); 
    for(var i = 0; i < textArr.length; i++) { 
     for(var j = 0; j < contentArr.length; j++) { 
      result += textArr[i] === contentArr[j] ? 1 : 0; 
     } 
    } 
    return result; 
} 

db.documents.find().forEach(function(doc){ 
    doc["total"] = doc["text"].total(doc["content"]); 
    print(doc); 
    // Save again with total value 
    //db.documents.save(doc); 
}) 

結果:

{ 
    "_id" : ObjectId("569c0be30586bcb40f7d253a"), 
    "text" : "this is the first this is", 
    "content" : "this is this is", 
    "total" : 8 
} 
+0

其實,我想通了現在,但你應得的接受和給予好評,原因很明顯 –