$project - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$project

Amazon DocumentDB の $project演算子を使用すると、出力ドキュメントにフィールドを選択的に含めたり除外したり、値を次のパイプラインステージに渡したり、入力ドキュメント値から新しいフィールドを計算したりできます。

パラメータ

  • field: 出力ドキュメントに含めるか除外するフィールドは、フィールドパス (例:「a.b.c」) にすることができます。

  • 1 または true: 出力に フィールドが含まれます。

  • 0 または false: 出力から フィールドを除外します。

例 (MongoDB シェル)

次の例は、学生コレクションでの $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フィールドが出力から除外され、他のすべてのフィールド (namemath、) が表示されますscience

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()