本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$match
Amazon DocumentDB 中的$match管道階段用於將輸入文件篩選為僅符合指定查詢條件的文件。這是彙總操作中最常用的管道階段之一。$match 階段會在任何其他管道階段之前套用,讓您有效率地減少後續階段需要處理的文件數量。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $match階段,根據特定欄位值篩選文件。
建立範例文件
db.collection.insertMany([
{ _id: 1, name: "John", age: 25, city: "New York" },
{ _id: 2, name: "Jane", age: 30, city: "Los Angeles" },
{ _id: 3, name: "Bob", age: 35, city: "Chicago" },
{ _id: 4, name: "Alice", age: 40, city: "Miami" }
]);
查詢範例
db.collection.aggregate([
{ $match: { age: { $gt: 30 } } },
{ $project: { _id: 1, name: 1, city: 1 } }
]);
輸出
[
{ "_id": 3, "name": "Bob", "city": "Chicago" },
{ "_id": 4, "name": "Alice", "city": "Miami" }
]
$match 階段會篩選文件,只包含age欄位大於 30 的文件。
程式碼範例
若要檢視使用 $match命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('collection');
const result = await collection.aggregate([
{ $match: { age: { $gt: 30 } } },
{ $project: { _id: 1, name: 1, city: 1 } }
]).toArray();
console.log(result);
await client.close();
}
example();
- Python
-
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['collection']
result = list(collection.aggregate([
{ '$match': { 'age': { '$gt': 30 } } },
{ '$project': { '_id': 1, 'name': 1, 'city': 1 } }
]))
print(result)
client.close()
example()