$project - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$project

Amazon DocumentDB 中的$project運算子可讓您選擇性地從輸出文件中包含或排除欄位、將值傳遞至下一個管道階段,以及從輸入文件值運算新欄位。

參數

  • field:要從輸出文件中包含或排除的欄位,可以是欄位路徑 (例如 "a.b.c")。

  • 1true:在輸出中包含 欄位。

  • 0false:從輸出中排除 欄位。

範例 (MongoDB Shell)

下列範例示範在學生集合上使用 $project 運算子

建立範例文件

db.students.insertMany([ { "_id": 1, "name": "Alejandro Rosalez", "math": 85, "science": 92, "grade": "A" }, { "_id": 2, "name": "Carlos Salazar", "math": 78, "science": 84, "grade": "B" }, { "_id": 3, "name": "Nikhil Jayashankar", "math": 95, "science": 89, "grade": "A" }, { "_id": 4, "name": "Shirley Rodriguez", "math": 72, "science": 76, "grade": "B" } ]);

此查詢僅包含輸出中的 namemath 欄位。除非明確排除,否則預設會包含 _id 欄位。

db.students.aggregate([ { $project: { "name": 1, "math": 1 } } ])

輸出

{ _id: 1, name: "Alejandro Rosalez", math: 85 } { _id: 2, name: "Carlos Salazar", math: 78 } { _id: 3, name: "Nikhil Jayashankar", math: 95 } { _id: 4, name: "Shirley Rodriguez", math: 72 }

此查詢會從輸出中排除 grade_id 欄位,顯示所有其他欄位 (namemathscience)。

db.students.aggregate([ { $project: { "grade": 0, "_id": 0 } } ])

輸出

{ name: "Alejandro Rosalez", math: 85, science: 92 } { name: "Carlos Salazar", math: 78, science: 84 } { name: "Nikhil Jayashankar", math: 95, science: 89 } { name: "Shirley Rodriguez", math: 72, science: 76 }

程式碼範例

若要檢視使用 $project命令的程式碼範例,請選擇您要使用的語言標籤:

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('students'); const result = await collection.aggregate([ { $project: { "name": 1, "math": 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['students'] result = list(collection.aggregate([ { '$project': { 'name': 1, 'math': 1 } } ])) print(result) client.close() example()