适用对象: MongoDB vCore
聚合管道中的 $match
阶段用于筛选与指定条件匹配的文档。 其与 find
操作类似,但在聚合管道中使用,以缩小传递至下一阶段的文档。 通过减少后续阶段中需要处理的文档数量,此阶段对于优化性能非常有用。
语法
$match
阶段的基本语法如下所示:
{
$match: {
<query>
}
}
说明 | |
---|---|
<query> |
一个标准的 MongoDB 查询文档,指定文档必须满足的条件。 |
示例
让我们通过以下示例 json 来了解用法。
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"staff": {
"totalStaff": {
"fullTime": 2,
"partTime": 0
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
}
],
"fullSales": 3700
},
"promotionEvents": [
{
"eventName": "Bargain Blitz Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 3,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 2,
"Day": 18
}
},
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
],
"tag": [
"#ShopLocal",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
示例 1:使用字符串比较来匹配文档
筛选 _id
为“7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5”的文档:
db.stores.aggregate([
{
$match: {
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}
}
])
此查询将返回示例文档。
示例 2:使用数字比较来匹配文档
筛选总销售额高于 $35,000 的文档:
db.stores.aggregate([
{
$match: {
"sales.totalSales": { $gt: 35000 }
}
},
// Limit the result to the first 3 documents
{ $limit: 3 },
// Include only _id and name fields in the output
{ $project: { _id: 1, name: 1 } }
])
此查询将返回以下文档。
[
{
"_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
"name": "Northwind Traders | Bed and Bath Place - West Oraland"
},
{
"_id": "57cc4095-77d9-4345-af20-f8ead9ef0197",
"name": "Wide World Importers | Bed and Bath Store - West Vitafort"
},
{
"_id": "560099f8-325f-4c35-a4e5-2e0879eb95af",
"name": "Wide World Importers | Bed and Bath Depot - North Maritzaberg"
}
]
示例 3:匹配子文档中的文档
筛选 DJ 混音器上有 15% 折扣的文档:
db.stores.aggregate([
{
$match: {
"promotionEvents.discounts": {
$elemMatch: {
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
}
}
},
// Limit the result to the first 3 documents
{ $limit: 3 },
// Include only _id and name fields in the output
{ $project: { _id: 1, name: 1 } }
])
此查询将返回以下文档。
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile"
},
{
"_id": "3c7eda41-23a1-4226-abf6-17ee9e851b5b",
"name": "Boulder Innovations | DJ Equipment Bazaar - New Ceasarview"
},
{
"_id": "63831a7d-13a9-4d8b-bf1d-ac004057f96d",
"name": "Contoso, Ltd. | DJ Equipment Shop - Reillyfurt"
}
]