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

布尔

如果针对分析字段运行查询,则必须设置为 true

no

false

score

对象

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

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

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

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

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

no

wildcard 是术语级操作符,这意味着不分析 query字段。通过将 allowAnalyzedField 选项设置为 true,可以在索引期间使用 wildcard操作符对分析字段执行搜索。如果将 wildcardallowAnalyzedField: true 一起使用, MongoDB Search 将根据该字段的指定分析器或自定义分析器应用字符筛选器和词元筛选器。MongoDB Search 跳过分词,输出始终是单个词元。

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

例子

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

例子

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

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

例子

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

"*\\**"

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

注意

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

"*\\\*"

➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。


movies以下示例将sample_mflix 数据库中的 集合与使用关键字分析器的自定义索引定义结合使用。如果集群上有示例数据集,则可以在 movies集合上创建MongoDB搜索索引,并在集群上运行示例查询。

Search Tester 中查看和编辑查询语法:

1

您可以从 Search & Vector Search 选项或 Data Explorer 转到MongoDB搜索页面。

2
  1. 单击要查询的索引右侧的 Query 按钮。

  2. 单击Edit Query查看 JSON格式的默认查询语法示例。

如要了解如何在 Atlas 用户界面中运行以下查询,请参阅定义您的查询。

mongosh 提示符处运行以下命令以使用 sample_mflix 数据库:

use sample_mflix

如要了解如何在 mongosh 中运行以下查询,请参阅定义您的查询。

如要了解如何在 MongoDB Compass 中运行以下查询,请参阅定义您的查询。

如要了解如何使用 MongoDB C# 驱动程序运行以下查询,请参阅定义您的查询。

如要了解如何使用 MongoDB Go# 驱动程序运行以下查询,请参阅定义您的查询。

如要了解如何使用 MongoDB Java 驱动程序运行以下查询,请参阅定义您的查询。

如要了解如何使用 MongoDB Kotlin 驱动程序运行以下查询,请参阅 定义您的查询。

如要了解如何使用 MongoDB 节点驱动程序运行以下查询,请参阅定义您的查询。

如要了解如何使用 PyMongo 驱动程序运行以下查询,请参阅定义您的查询。

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

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

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

将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。

[
{
$search: {
"wildcard": {
"path": "title",
"query": "Green D*"
}
}
}
]
SCORE: 1 _id: "573a1393f29313caabcddaf5"
plot: "Sophie loved Edmund, but he left town when her parents forced her to m…"
genres: Array
runtime: 141
SCORE: 1 _id: "573a13a2f29313caabd0a4e4"
plot: "The story of some Vietnamese refugees as they first arrive at Camp Pen…"
genres: Array
runtime: 115

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

db.movies.aggregate([
{
"$search": {
"wildcard": {
"path": "title",
"query": "Green D*"
}
}
},
{
"$project": {
"_id": 0,
"title": 1
}
}
])
{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
In the :guilabel:`Aggregations` tab of the ``movies`` collection,
configure each of the following pipeline stages by selecting the stage
from the dropdown and adding the query for that stage. Click
:guilabel:`Add Stage` to add additional stages.
.. list-table::
:header-rows: 1
:widths: 25 75
* - Pipeline Stage
- Query
* - ``$search``
- .. code-block:: javascript
{
"wildcard": {
"query": "Green D*",
"path": "title"
}
}
* - ``$project``
- .. code-block:: javascript
{
"_id": 0,
"title": 1,
}
{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class WildcardSingleCharacter
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Green D*"))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}
{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"wildcard", bson.D{{"path", "title"}, {"query", "Green D*"}}}}}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}
[{title Green Dolphin Street}]
[{title Green Dragon}]
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class WildcardSingleCharacter {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("query", "Green D*").append("path", "title");
// run pipeline and print results
collection.aggregate(Arrays.asList(
eq("$search", eq("wildcard", agg)),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}
{"title": "Green Dolphin Street"}
{"title": "Green Dragon"}
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Filters.eq
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document("query", "Green D*").append("path", "title")
val resultsFlow = collection.aggregate<Document>(
listOf(
eq("\$search", eq("wildcard", agg)),
project(fields(
excludeId(),
include("title")
))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}
Document{{title=Green Dolphin Street}}
Document{{title=Green Dragon}}
const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {wildcard: {query: "Green D*", path: "title"}}},
{$project: {_id: 0, title: 1}},
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);
{ title: 'Green Dolphin Street' }
{ title: 'Green Dragon' }
import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"wildcard": {"query": "Green D*", "path": "title"}}},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)
{'title': 'Green Dolphin Street'}
{'title': 'Green Dragon'}

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

将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。

[
{
$search: {
"wildcard": {
"path": "title",
"query": "Wom?n *"
}
}
}
]
SCORE: 1 _id: "573a1393f29313caabcdcbdd"
plot: "Rival reporters Sam and Tess fall in love and get married, only to fin…"
genres: Array
runtime: 114
SCORE: 1 _id: "573a1394f29313caabce08c6"
plot: "A married, middle-aged woman is shocked to discover that her husband, …"
genres: Array
runtime: 93
SCORE: 1 _id: "573a1396f29313caabce42e5"
plot: "The battle of the sexes and relationships among the elite of Britian's…"
genres: Array
runtime: 131
SCORE: 1 _id: "573a1398f29313caabceb06d"
fullplot: "A woman's lover leaves her, and she tries to contact him to find out w…"
imdb: Object
year: 1988
SCORE: 1 _id: "573a139df29313caabcf9c83"
plot: "A new woman comes between a widower and his adult son."
genres: Array
runtime: 110
SCORE: 1 _id: "573a13a0f29313caabd050bf"
fullplot: "Isabella is a great cook, making her husband's restaurant in Bahia, Br…"
imdb: Object
year: 2000
SCORE: 1 _id: "573a13aaf29313caabd22c05"
countries: Array
genres: Array
runtime: 115
SCORE: 1 _id: "573a13aef29313caabd2d899"
countries: Array
genres: Array
runtime: 72
SCORE: 1 _id: "573a13aff29313caabd32566"
fullplot: "An adaptation of Bishop T.D. Jakes' self-help novel, chronciling a wom…"
imdb: Object
year: 2004
SCORE: 1 _id: "573a13b0f29313caabd332de"
fullplot: "Two college friends get together and reminisce on the woman they both …"
imdb: Object
year: 2004

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

$limit 阶段将结果限制为 5 个文档,而 $project 阶段将结果限制为仅 title 字段。

db.movies.aggregate([
{
"$search": {
"wildcard": {
"path": "title",
"query": "Wom?n *"
}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 0,
"title": 1
}
}
])
[
{ title: 'Woman of the Year' },
{ title: 'Woman in a Dressing Gown' },
{ title: 'Women in Love' },
{ title: 'Women on the Verge of a Nervous Breakdown' },
{ title: 'Woman Wanted' }
]

$limit 阶段将结果限制为 5 个文档,而 $project 阶段将结果限制为仅 title 字段。

In the :guilabel:`Aggregations` tab of the ``movies`` collection,
configure each of the following pipeline stages by selecting the stage
from the dropdown and adding the query for that stage. Click
:guilabel:`Add Stage` to add additional stages.
.. list-table::
:header-rows: 1
:widths: 25 75
* - Pipeline Stage
- Query
* - ``$search``
- .. code-block:: javascript
{
"wildcard": {
"query": "Wom?n *",
"path": "title"
}
}
* - ``$limit``
- .. code-block:: javascript
5
* - ``$project``
- .. code-block:: javascript
{
"_id": 0,
"title": 1,
}
{ title: 'Woman of the Year' },
{ title: 'Woman in a Dressing Gown' },
{ title: 'Women in Love' },
{ title: 'Women on the Verge of a Nervous Breakdown' },
{ title: 'Woman Wanted' }

$limit 阶段将结果限制为 5 个文档,而 $project 阶段将结果限制为仅 title 字段。

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class WildcardMultipleCharacter
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Wom?n *"))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.Limit(5)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}
{ title: 'Woman of the Year' },
{ title: 'Woman in a Dressing Gown' },
{ title: 'Women in Love' },
{ title: 'Women on the Verge of a Nervous Breakdown' },
{ title: 'Woman Wanted' }

$limit 阶段将结果限制为 5 个文档,而 $project 阶段将结果限制为仅 title 字段。

package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(options.Client().ApplyURI("<connection-string"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"wildcard", bson.D{{"path", "title"}, {"query", "Wom?n *"}}}}}}
limitStage := bson.D{{"$limit", 5}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}

$limit 阶段将结果限制为 5 个文档,而 $project 阶段将结果限制为仅 title 字段。

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class WildcardMultiCharacter {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespsace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("query", "Wom?n *").append("path", "title");
// run pipeline and print results
collection.aggregate(Arrays.asList(
eq("$search", eq("wildcard", agg)),
limit(5),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}
[{title Woman of the Year}]
[{title Woman in a Dressing Gown}]
[{title Women in Love}]
[{title Women on the Verge of a Nervous Breakdown}]
[{title Woman Wanted}]

$limit 阶段将结果限制为 5 个文档,而 $project 阶段将结果限制为仅 title 字段。

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Filters.eq
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document("query", "Wom?n *").append("path", "title")
val resultsFlow = collection.aggregate<Document>(
listOf(
eq("\$search", eq("wildcard", agg)),
limit(5),
project(fields(
excludeId(),
include("title")
))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}
{"title": "Woman of the Year"}
{"title": "Woman in a Dressing Gown"}
{"title": "Women in Love"}
{"title": "Women on the Verge of a Nervous Breakdown"}
{"title": "Woman Wanted"}

$limit 阶段将结果限制为 5 个文档,而 $project 阶段将结果限制为仅 title 字段。

const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {wildcard: {query: "Wom?n *", path: "title"}}},
{$limit: 5},
{$project: {_id: 0,title: 1}}
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);
{ title: 'Woman of the Year' }
{ title: 'Woman in a Dressing Gown' }
{ title: 'Women in Love' }
{ title: 'Women on the Verge of a Nervous Breakdown' }
{ title: 'Woman Wanted' }

$limit 阶段将结果限制为 5 个文档,而 $project 阶段将结果限制为仅 title 字段。

import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"wildcard": {"query": "Wom?n *", "path": "title"}}},
{"$limit": 5},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)
{'title': 'Woman of the Year'}
{'title': 'Woman in a Dressing Gown'}
{'title': 'Women in Love'}
{'title': 'Women on the Verge of a Nervous Breakdown'}
{'title': 'Woman Wanted'}

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

注意

以下示例将在 mongosh 中运行。有关在驱动程序中使用转义字符的更多信息,请参阅转义字符行为

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

将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。

[
{
$search: {
"wildcard": {
"path": "title",
"query": "*\\?"
}
}
}
]
SCORE: 1 _id: "573a1390f29313caabcd5ea4"
plot: "A District Attorney's outspoken stand on abortion gets him in trouble …"
genres: Array
runtime: 62
SCORE: 1 _id: "573a1392f29313caabcdab4a"
plot: "Robin is crooning to a Mae West-like Jenny Wren when he is shot with a…"
genres: Array
runtime: 8
SCORE: 1 _id: "573a1394f29313caabce08ab"
plot: "Elmer Fudd is again hunting rabbits - only this time it's an opera. Wa…"
genres: Array
runtime: 7
SCORE: 1 _id: "573a1394f29313caabce08c8"
plot: "To save his career, an ad man wants a sex symbol to endorse a lipstick…"
genres: Array
runtime: 93
SCORE: 1 _id: "573a1395f29313caabce1555"
plot: "In order to get back into the good graces with his wife with whom he h…"
genres: Array
runtime: 115
SCORE: 1 _id: "573a1395f29313caabce1dce"
plot: "A former child star torments her crippled sister in a decaying Hollywo…"
genres: Array
runtime: 134
SCORE: 1 _id: "573a1395f29313caabce2422"
plot: "Roger Willoughby is considered to be a leading expert on sports fishin…"
genres: Array
runtime: 120
SCORE: 1 _id: "573a1395f29313caabce2d63"
plot: "The true story of the departure of the German occupiers from Paris in …"
genres: Array
runtime: 173
SCORE: 1 _id: "573a1395f29313caabce2db5"
plot: "In this excoriating satire of the fashion industry, Polly Maggoo is a …"
genres: Array
runtime: 101
SCORE: 1 _id: "573a1395f29313caabce2ecc"
plot: "A bitter aging couple with the help of alcohol, use a young couple to …"
genres: Array
runtime: 131

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

db.movies.aggregate([
{
"$search": {
"wildcard": {
"path": "title",
"query": "*\\?"
}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 0,
"title": 1
}
}
])
{ "title" : "Where Are My Children?" }
{ "title" : "Who Killed Cock Robin?" }
{ "title" : "What's Opera, Doc?" }
{ "title" : "Will Success Spoil Rock Hunter?" }
{ "title" : "Who Was That Lady?" }

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

In the :guilabel:`Aggregations` tab of the ``movies`` collection,
configure each of the following pipeline stages by selecting the stage
from the dropdown and adding the query for that stage. Click
:guilabel:`Add Stage` to add additional stages.
.. list-table::
:header-rows: 1
:widths: 25 75
* - Pipeline Stage
- Query
* - ``$search``
- .. code-block:: javascript
{
"wildcard": {
"query": "*\\?",
"path": "title"
}
}
* - ``$limit``
- .. code-block:: javascript
5
* - ``$project``
- .. code-block:: javascript
{
"_id": 0,
"title": 1,
}
{ "title" : "Where Are My Children?" }
{ "title" : "Who Killed Cock Robin?" }
{ "title" : "What's Opera, Doc?" }
{ "title" : "Will Success Spoil Rock Hunter?" }
{ "title" : "Who Was That Lady?" }

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class WildcardEscapeCharacter
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "*\\?"))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.Limit(5)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}
{ "title" : "Where Are My Children?" }
{ "title" : "Who Killed Cock Robin?" }
{ "title" : "What's Opera, Doc?" }
{ "title" : "Will Success Spoil Rock Hunter?" }
{ "title" : "Who Was That Lady?" }

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"wildcard", bson.D{{"path", "title"}, {"query", "*\\?"}}}}}}
limitStage := bson.D{{"$limit", 5}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}
[{title Where Are My Children?}]
[{title Who Killed Cock Robin?}]
[{title What's Opera, Doc?}]
[{title Will Success Spoil Rock Hunter?}]
[{title Who Was That Lady?}]

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class WildcardEscapeCharacter {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("query", "*\\?").append("path", "title");
// run pipeline and print results
collection.aggregate(Arrays.asList(
eq("$search", eq("wildcard", agg)),
limit(5),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}
{"title": "Where Are My Children?"}
{"title": "Who Killed Cock Robin?"}
{"title": "What's Opera, Doc?"}
{"title": "Will Success Spoil Rock Hunter?"}
{"title": "Who Was That Lady?"}

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Filters.eq
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document("query", "*\\?").append("path", "title")
val resultsFlow = collection.aggregate<Document>(
listOf(
eq("\$search", eq("wildcard", agg)),
limit(5),
project(fields(
excludeId(),
include("title")
))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}
Document{{title=Who Are You, Polly Magoo?}}
Document{{title=Where Were You When the Lights Went Out?}}
Document{{title=Why Does Herr R. Run Amok?}}
Document{{title=What's Up, Doc?}}
Document{{title=Who Is Killing the Great Chefs of Europe?}}

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {wildcard: {query: "*\\?", path: "title"}}},
{$limit: 5},
{$project: {_id: 0,title: 1}}
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);
{ title: 'Where Are My Children?' }
{ title: 'Who Killed Cock Robin?' }
{ title: "What's Opera, Doc?" }
{ title: 'Will Success Spoil Rock Hunter?' }
{ title: 'Who Was That Lady?' }

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"wildcard": {"query": "*\\?", "path": "title"}}},
{"$limit": 5},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)
{'title': 'Where Are My Children?'}
{'title': 'Who Killed Cock Robin?'}
{'title': "What's Opera, Doc?"}
{'title': 'Will Success Spoil Rock Hunter?'}
{'title': 'Who Was That Lady?'}

以下查询使用 $searchMeta 阶段来搜索在 title 字段中任意位置包含术语 summer 的电影,并检索每个类别中符合条件的电影数量。

db.movies.aggregate([
{
"$searchMeta": {
"facet": {
"operator": {
"wildcard": {
"path": "title",
"query": "*summer*"
}
},
"facets": {
"genresFacet": {
"type": "string",
"path": "genres"
}
}
}
}
}
])
[
{
count: { lowerBound: Long('6') },
facet: {
genresFacet: {
buckets: [
{ _id: 'Comedy', count: Long('5') },
{ _id: 'Fantasy', count: Long('3') },
{ _id: 'Romance', count: Long('3') },
{ _id: 'Drama', count: Long('2') },
{ _id: 'Horror', count: Long('1') },
{ _id: 'Mystery', count: Long('1') }
]
}
}
}
]

后退

text

在此页面上