我在集合messages
中有字段message
,例如:
[
{
_id: "chrYMAqT8meXpqdrC",
message: "Hello world. This is mongo"
},
{
_id: "rKu5gf5zL6NaSvZ5Q",
message: "Hello. This is mongo world"
},
{
_id: "rKu5gf5zL6NaSvZ5Q",
message: "world. This is mongo Hello"
}
]
我想要搜索 message
字段包含 /Hello world/ig
或 message
字段包含单词 的消息>你好
和单词
。最重要的是 - 必须按照输入字符串的顺序找到单词,因此不得找到集合中的最后一个元素,但必须找到前两个元素。我知道如何通过与正则表达式匹配来查找,但在第二种情况下我不明白该怎么做
最佳答案
您可以将 $regex
与正则表达式 Hello.*world
一起使用。另外this
db.collection.find({
message: {
$regex: "Hello.*world",
$options: "i"
}
})
或者你可以使用$regexMatch
db.collection.find({
$expr: {
$regexMatch: {
input: "$message",
regex: "Hello.*world",
options: "i"
}
}
})
])
选项:“i”
表示不区分大小写。如果您不需要,请将其删除
关于node.js - MongoDB:通过输入字符串或输入字符串中的单个单词的匹配进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76429017/