2014-10-27 56 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