环境:
- MongoDB(3.2.0)与Mongoose
集合:
- 用户
文本索引创建:
BasicDBObject keys = new BasicDBObject();
keys.put("name","text");
BasicDBObject options = new BasicDBObject();
options.put("name", "userTextSearch");
options.put("unique", Boolean.FALSE);
options.put("background", Boolean.TRUE);
userCollection.createIndex(keys, options); // using MongoTemplate
文档:
- {"name":"LEONEL"}
查询:
db.users.find( { "$text" : { "$search" : "LEONEL" } } )
=> 找到db.users.find( { "$text" : { "$search" : "leonel" } } )
=> 找到(搜索区分大小写为false)db.users.find( { "$text" : { "$search" : "LEONÉL" } } )
=> 找到(搜索区分变音符号为false)db.users.find( { "$text" : { "$search" : "LEONE" } } )
=> 找到(部分匹配搜索)db.users.find( { "$text" : { "$search" : "LEO" } } )
=> 没有找到(部分匹配搜索)db.users.find( { "$text" : { "$search" : "L" } } )
=> 没有找到(部分匹配搜索)
为什么使用"LEO"或"L"作为查询条件会得到0个结果呢?
不允许在文本索引搜索中使用正则表达式。
db.getCollection('users')
.find( { "$text" : { "$search" : "/LEO/i",
"$caseSensitive": false,
"$diacriticSensitive": false }} )
.count() // 0 results
db.getCollection('users')
.find( { "$text" : { "$search" : "LEO",
"$caseSensitive": false,
"$diacriticSensitive": false }} )
.count() // 0 results
MongoDB文档:
/LEO/i
吗?你可以在MongoDB中使用正则表达式来搜索值。 - BrTkCa