英文:
MongoDB: search by match of the input string or single words from the input string
问题
我想要搜索包含 /Hello world/ig
或包含单词 Hello
和 word
的消息,而且最重要的是 - 这些单词必须按输入字符串的顺序找到,所以集合中的最后一个元素不应该被找到,但前两个必须被找到。我知道如何使用正则表达式进行匹配,但在第二种情况下,我不明白该如何做。
英文:
I have field message
in a collection messages
, for example:
[
{
_id: "chrYMAqT8meXpqdrC",
message: "Hello world. This is mongo"
},
{
_id: "rKu5gf5zL6NaSvZ5Q",
message: "Hello. This is mongo world"
},
{
_id: "rKu5gf5zL6NaSvZ5Q",
message: "world. This is mongo Hello"
}
]
I want to search for messages where the message
field contains /Hello world/ig
or where the message
field contains the words Hello
and word
. And most importantly - the words must be found in the order of the input string, so the last element in the collection must not be found, but the first two must. I know how to find by matching with regex, but in the second case i don't understand how to do it
答案1
得分: 2
你可以使用 $regex
与正则表达式 Hello.*world
。也可以使用 这个。
db.collection.find({
message: {
$regex: "Hello.*world",
$options: "i"
}
})
或者你可以使用 $regexMatch
。
db.collection.find({
$expr: {
$regexMatch: {
input: "$message",
regex: "Hello.*world",
options: "i"
}
}
})
options: "i"
表示大小写不敏感。如果不需要,可以移除它。
英文:
you could use $regex
with the regex Hello.*world
. Also this
db.collection.find({
message: {
$regex: "Hello.*world",
$options: "i"
}
})
or you could use $regexMatch
db.collection.find({
$expr: {
$regexMatch: {
input: "$message",
regex: "Hello.*world",
options: "i"
}
}
})
])
options: "i"
means case-insensitive. remove that if you don't want it
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论