我试图在多个字段中查找搜索字符串中的所有字词。例如:
如果我要搜索" java咖啡"在这个数据中:
{ _id: 1, name: "Java Hut", description: "Coffee and cakes" },
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
{ _id: 3, name: "Coffee Shop", description: "Just coffee" },
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
{ _id: 5, name: "Java Shopping", description: "Indonesian goods Hut" },
{ _id: 6, name: "Java Coffee", description: "goods Hut" },
{ _id: 7, name: "Coffee Shop", description: "Just coffee Java" }
我希望它能够在每个字段中单独搜索每个单词,并返回在任何指定字段中包含每个搜索单词的所有文档。
由于这些匹配,我应该将ids 1,6和7作为结果返回:
{ _id: 1, name: "**Java** Hut", description: "**Coffee** and cakes" },<br>
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },<br>
{ _id: 3, name: "Coffee Shop", description: "Just coffee" },<br>
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },<br>
{ _id: 5, name: "Java Shopping", description: "Indonesian goods Hut" },<br>
{ _id: 6, name: "**Java Coffee**", description: "goods Hut" },<br>
{ _id: 7, name: "Coffee Shop", description: "Just **coffee Java**" }
关于如何以有效的方式实现Mongo执行它的任何想法?
答案 0 :(得分:4)
您可以在集合中添加text
index,以便在多个字段中启用文字搜索。在这种情况下:
db.test.createIndex({name: 'text', description: 'text'})
然后,找到包含&#34; java&#34;的文档。和&#34;咖啡&#34;在任一字段中,您都可以使用引用的两个单词执行text search查询,以要求找到这两个单词。引用单词将它们转换为phrases,它调用逻辑AND行为而不是OR。
db.test.find({$text: {$search: '"java" "coffee"'}})
答案 1 :(得分:1)
如果搜索字符串是以空格分隔的字符串,$ text运算符会对每个术语执行逻辑OR搜索,并返回包含任何术语的文档。
db.collection.find( { $text: { $search: "java coffee" } } )
查询将返回该集合的任何文档中的coffee或java。
有关详细信息,请参阅manual。