Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs 菜单
Docs 主页
/ /

wildcard Operator

wildcard

wildcard 操作符在搜索字符串中使用可匹配任何字符的特殊字符进行查询。

字符
说明

?

匹配任意单个字符。

*

匹配 0 个或更多字符。

\

转义字符。

wildcard 为词级操作符,因而不会分析 query 字段。术语级操作符非常适合 关键字分析器,因为 query 字段被视为包含特殊字符的单个术语。有关查询已分析的 query 字段的示例,请参阅 已分析字段示例。

wildcard 通过以下语法实现:

{
$search: {
"index": <index name>, // optional, defaults to "default"
"wildcard": {
"query": "<search-string>",
"path": "<field-to-search>",
"allowAnalyzedField": <boolean>,
"score": <options>
}
}
}

wildcard 使用以下词条来构造查询:

字段
类型
说明
必要性
默认

query

字符串或字符串数组

要搜索的一个或多个字符串。

path

字符串或字符串数组

要搜索的一个或多个带索引字段。您还可以指定通配符路径进行搜索。

allowAnalyzedField

布尔

Set to true if you run your query against a field indexed with a tokenizing analyzer. This avoids the field's analyzer from splitting the indexed value into many terms. Fields indexed with the Keyword Analyzer don't require this option.

no

false

score

对象

修改分配给匹配搜索词结果的分数。选项包括:

  • boost将生成的分数乘以给定数字。

  • constant将结果分数替换为给定数字。

  • function:使用给定的表达式替换结果分数。

有关在查询中使用 score 的信息,请参阅对结果中的文档进行评分

no

wildcard is a term-level operator, meaning that the query field isn't analyzed. Use the wildcard operator on fields indexed with tokenizing analyzers by setting allowAnalyzedField to true. Fields indexed with the Keyword Analyzer already treat the field value as a single term, so allowAnalyzedField: true isn't required.

If you use wildcard with allowAnalyzedField: true, MongoDB Search applies character filters and token filters based on the specified analyzer or custom analyzer for the field. MongoDB Search skips the tokenization and the output is always a single token.

以下示例显示 wildcard 操作符在对已分析字段执行搜索时的行为方式:

例子

foo bar baz假设使用标准分析器对字段 进行了索引。MongoDB Search 会分析字段并将其索引为 foobarbaz。在此字段中搜索 foo bar* 找不到任何结果,因为通配符操作符将 foo bar* 视为结尾带有通配符的单个搜索术语。换句话说, MongoDB Search 在字段中搜索以 foo bar 开头的任何术语,但找不到任何结果,因为不存在这样的术语。

例子

在使用关键字分析器进行索引的字段上搜索 *Star Trek*,即可查找该字段在任何上下文中包含字符串 Star Trek 的所有文档。在使用标准分析器进行索引的字段上搜索 *Star Trek* 找不到任何结果,因为 StarTrek 之间有空格,而索引不包含空格。

mongosh 中或驱动程序中使用转义字符时,必须在要转义的字符前使用双反斜杠。

例子

要创建一个通配符表达式来搜索聚合管道中包含字面星号的任何字符串,请使用以下表达式:

"*\\**"

第一个和最后一个星号作为通配符,可匹配任何字符,而 \\* 则匹配文字星号。

注意

使用以下表达式对文本反斜杠进行转义:

"*\\\*"

The following examples use the movies collection in the sample_mflix database with a custom index definition that uses the keyword analyzer. If you have the sample dataset on your cluster, you can create a MongoDB Search index on the movies collection and run the example queries on your cluster.

以下索引定义使用关键字分析器movies 集合中的 title 字段进行索引:

1{
2 "mappings": {
3 "fields": {
4 "title": {
5 "analyzer": "lucene.keyword",
6 "type": "string"
7 }
8 }
9 }
10}

以下示例在所有 title 字段中搜索以 Green D 开头、后跟任意数量的其他字符的电影标题。

以下示例在所有 title 字段中搜索以字符串 Wom?n(其中 ? 可以是任意单个字符)开头的电影标题,然后是空格,然后是任意数量的其他字符。

以下示例使用转义字符搜索 title 字段以问号结尾的文档。

query 字段中的 * 字符与任何字符匹配,而 \\? 字符串与文字问号匹配。

后退

Vector Search

在此页面上