$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 필드를 제외하여 다른 모든 필드(, name, mathscience)를 표시합니다.

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