对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$match(聚合阶段)

$match

根据指定的查询谓词筛选文档。匹配的文档将传递到下一个管道阶段。

可以使用 $match 查找托管在以下环境中的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
{ $match: { <query predicate> } }

$match 查询谓词的语法与 find() 命令的查询参数中使用的语法相同。

要在查询谓词中包含表达式,请使用 $expr 操作符。

如果满足以下条件之一,则 $match 阶段会从管道结果中过滤掉文档:

  • $match查询谓词返回该文档的 0、null 或 false 值。

  • $match查询谓词使用了该文档中缺少的字段。

  • 您不能在 $match 阶段使用 $where。

  • 您不能在 $match 阶段中使用 $near 或 $nearSphere。或者也可以:

  • To use $text in a $match stage, the $match stage has to be the first stage of the pipeline.

    视图不支持 $text。

    注意

    $text provides text query capabilities for self-managed (non-Atlas) deployments. For data hosted on MongoDB Atlas, MongoDB offers an improved full-text query solution, Atlas Search.

For data stored in MongoDB Atlas, you can use the Atlas Search compound Operator operator filter option to match or filter documents when running $search queries. Running $match after $search is less performant than running $search with the compound Operator operator filter option.

要了解有关 filter 选项的更多信息,请参阅 Atlas 文档中的复合操作符。

本页上的示例使用来自 sample_mflix 数据集的数据。有关如何将此数据集加载到您的自管理 MongoDB 部署中的详细信息,请参阅 加载示例数据集。如果您对示例数据库进行了任何修改,您可能需要删除并重新创建数据库,才能运行此页面上的示例。

The following operation uses $match to perform an equality match on the rated field. The runtime filter limits the result to a small, representative set:

db.movies.aggregate(
[ { $match : { rated : "TV-PG", runtime : { $gt: 1000 } } } ]
)

The $match selects the documents where the rated field equals "TV-PG" and runtime is greater than 1000.

The following example selects documents to process using the $match pipeline operator and then pipes the results to the $group pipeline operator to compute a count of the documents:

db.movies.aggregate( [
{ $match: { $or: [
{ runtime: { $gt: 1000 } },
{ year: { $lt: 1910 } }
] } },
{ $group: { _id: null, count: { $sum: 1 } } }
] )
[ { _id: null, count: 6 } ]

In the aggregation pipeline, $match selects the documents where either the runtime is greater than 1000 or the year is earlier than 1910. These documents are then sent to the $group to perform a count.

要根据数组字段中的元素过滤 document,在 $match 阶段的查询谓词中使用 $elemMatch 操作符:

db.aggregate( [
{
$documents: [
{ student_id: 1, scores: [ 0.75, 0.65, 0.73 ] },
{ student_id: 2, scores: [ 0.9, 0.88, 0.98 ] },
{ student_id: 3, scores: [ 0.9, 0.84, 0.93 ] }
]
}, {
$match: {
scores: { $elemMatch: { $gte: 0.9 } }
}
}
] )
[
{ student_id: 2, scores: [ 0.9, 0.88, 0.98 ] },
{ student_id: 3, scores: [ 0.9, 0.84, 0.93 ] }
]

请参阅完整聚合管道教程,以获取有关聚合的更多信息和应用场景。