2014-10-27 55 views
0

我試圖在數據庫中搜索,但我沒有得到任何結果,並且找不到錯誤,我在控制檯中得到一個空數組,但數據庫中充滿了元素在這種情況下包括「a」。在mongod數據庫中搜索

如果我試圖查找數據庫中的所有內容,我會看到所有結果,所以它在$ search或$ text中的內容會打破腳本。

所有的幫助都非常感謝,我一直在坐着,撕裂我的頭髮幾天!

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 

var db; 

MongoClient.connect("mongodb://localhost:27017/insights", function(err, database) { 
    db = database; 
    db.collection("textstore", {}, function(err, coll) { 
    if (err != null) { 
    db.createCollection("textstore", function(err, result) { 
    assert.equal(null, err); 
    }); 
    } 
    db.ensureIndex("textstore", { 
    document: "text" 
    }, function(err, indexname) { 
    assert.equal(null, err); 
    }); 
    }); 
}); 

app.post("/search", function(req, res) { 
    db.collection('textstore').find({"$text": {"$search": 'a'}}).toArray(function(err, items) { 
    console.log(items) 
    }) 
}); 

回答

2

搜索MongoDB text index是語言識別的,默認語言是英語。語言意識意味着某些非常普遍但通常沒有意義的單詞被忽略。英語中的單詞a就是這樣一個詞。這裏是t he relevant part from the documentation

MongoDB支持各種語言的文本搜索。文本索引刪除語言特定的停用詞(例如英語,「the」,「an」,「a」,「and」等),並使用簡單的特定於語言的後綴詞幹。

請嘗試搜索更有意義的內容或在搜索過程中通過將語言明確設置爲"none"來禁用語言認知。

db.collection('textstore').find({"$text": {"$search": 'a', $language:"none"}}) 

順便說一句,您還可以在創建索引時重寫默認語言,甚至可以在文檔和子文檔級別覆蓋它。欲瞭解更多信息,請致電check the documentation about specifying languages for text indexes