MongoDB文本搜索,查找全部排除

时间:2018-03-24 09:49:58

标签: mongodb

嗨,是否可以在此数据集中找到查询

{ "text" : "cake" }
{ "text" : "sale" }
{ "text" : "sale cake" }
{ "text" : "cake sale" }
{ "text" : "dress sale" }
{ "text" : "cake sale monday"

所有文件不包括word" monday"

我想得到这样的结果:

{ "text" : "cake" }
{ "text" : "sale" }
{ "text" : "sale cake" }
{ "text" : "cake sale" }
{ "text" : "dress sale" }
{ "text" : "cake sale" }

2 个答案:

答案 0 :(得分:0)

您可以尝试使用MongoDB正则表达式。 示例查询

db.example.find({text:{$not:/monday/, $regex:/cake/}})

有关MongoDB正则表达式的性能,请参阅this

答案 1 :(得分:0)

您也可以使用MongoDB文本搜索。首先,您需要创建文本搜索索引。

在书籍集合上为标题和类别字段创建索引

db.books.createIndex({title:'text', category:'text'})

然后使用$text运算符进行搜索,如

db.books.find({$text:{$search: 'mongodb'}}).pretty()

以上查询将在标题和类别字段中搜索mongodb文本。

如果您要搜索mongodb文本但想要排除包含初学者字词的结果,可以使用-作为初学者字词的前缀来完成

db.books.find({$text:{$search: 'mongodb -beginner'}}).pretty()

有关详情,请参阅$text Documentation

相关问题