在mongodb中找到一个或另一个词

时间:2022-08-22 21:17:08

I am new to MongoDB so I was wondering how do you search a document for one word or another especially if one word is phrase and another is single word.

我是MongoDB的新手,所以我想知道如何在一个或另一个单词中搜索文档,特别是如果一个单词是短语而另一个单词是单个单词。

Here if we have to search word printer or ink, we use the syntax below.

如果我们必须搜索word打印机或墨水,我们使用下面的语法。

db.supplies.runCommand("text", {search:"printer ink"})

What do I do if I want to find word "printer ink" or paper? Notice how Printer ink is a phrase. I tried

如果我想找到“打印机墨水”或纸张,我该怎么办?请注意打印机墨水是一个短语。我试过了

db.supplies.runCommand("text", {search:"\"printerink\" paper"}) 

but it didn't help so I am hoping someone could help me.

但它没有帮助所以我希望有人可以帮助我。

1 个解决方案

#1


Quoting the documentation

引用文档

If the $search string includes a phrase and individual terms, text search will only match the documents that include the phrase. More specifically, the search performs a logical AND of the phrase with the individual terms in the search string

如果$ search字符串包含短语和单个术语,则文本搜索将仅匹配包含该短语的文档。更具体地,搜索执行短语与搜索字符串中的各个词的逻辑AND

That being said to find word printer ink or paper you will need to run two different queries

据说要找到打印机墨水或纸张,你需要运行两个不同的查询

db.supplies.find({ $text: { $search: "\"printer ink\"" }})

and

db.supplies.find({ $text: { $search: "paper" }})

Instead you can use $regex operator if the task doesn't required the use of $text

相反,如果任务不需要使用$ text,则可以使用$ regex运算符

db.supplies.find({ <yourfield>: {"$in": [/printer ink/, /paper/] }})

#1


Quoting the documentation

引用文档

If the $search string includes a phrase and individual terms, text search will only match the documents that include the phrase. More specifically, the search performs a logical AND of the phrase with the individual terms in the search string

如果$ search字符串包含短语和单个术语,则文本搜索将仅匹配包含该短语的文档。更具体地,搜索执行短语与搜索字符串中的各个词的逻辑AND

That being said to find word printer ink or paper you will need to run two different queries

据说要找到打印机墨水或纸张,你需要运行两个不同的查询

db.supplies.find({ $text: { $search: "\"printer ink\"" }})

and

db.supplies.find({ $text: { $search: "paper" }})

Instead you can use $regex operator if the task doesn't required the use of $text

相反,如果任务不需要使用$ text,则可以使用$ regex运算符

db.supplies.find({ <yourfield>: {"$in": [/printer ink/, /paper/] }})