Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /

$ 프로젝트 (집계 단계)

$project

요청된 필드가 있는 문서를 파이프라인의 다음 단계로 전달합니다. 지정된 필드는 입력 문서의 기존 필드일 수도 있고 새로 계산된 필드일 수도 있습니다.

다음 환경에서 호스팅되는 배포에 $project 사용할 수 있습니다.

  • MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스

  • MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전

  • MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전

$project 단계의 프로토타입 형식은 다음과 같습니다.

{ $project: { <specification(s)> } }

$project는 필드 포함, _id 필드 표시 안 함, 새 필드 추가, 기존 필드 값 재설정을 지정할 수 있는 문서를 사용합니다. 또는 필드 제외를 지정할 수 있습니다.

$project 사양의 형식은 다음과 같습니다.

형식
설명

<field>: <1 or true>

필드 포함 여부를 지정합니다. 0이 아닌 정수도 true로 처리됩니다.

_id: <0 or false>

_id 필드의 억제를 지정합니다.

필드 조건부로 제외하려면 변수를 대신 REMOVE 사용하세요. 자세한내용은 조건부로 필드 제외를 참조하세요.

<field>: <expression>

새 필드를 추가하거나 기존 필드의 값을 재설정합니다.

표현식 $$REMOVE로 평가되면 해당 필드 출력에서 제외됩니다. 자세한내용은 조건부로 필드 제외를 참조하세요.

<field>: <0 or false>

필드 제외 여부를 지정합니다.

필드 조건부로 제외하려면 변수를 대신 REMOVE 사용하세요. 자세한내용은 조건부로 필드 제외를 참조하세요.

이외의 필드 제외하도록 지정하면 _id 다른 지정 양식을 $project 사용할 수 없습니다. 이 제한은 변수를 사용하여 필드 를 조건부로 제외하는 경우에는 적용 되지 않습니다.REMOVE

필드를 제외하려면 단계를 사용할 수도 $unset 있습니다.

  • _id 필드는 기본적으로 출력 문서에 포함됩니다. 입력 문서의 다른 필드를 출력 문서에 포함하려면 $project에 포함을 명시적으로 지정해야 합니다.

  • 문서에 존재하지 않는 필드의 포함을 지정하면 $project(은)는 해당 필드 포함을 무시하고 해당 필드를 문서에 추가하지 않습니다.

_id 필드는 출력 문서에 포함되도록 기본 설정되어 있습니다. 출력 문서에서 _id 필드를 제외하려면 $project에서 _id 필드를 사용하지 않음을 명시적으로 지정해야 합니다.

필드 제외를 지정하면 다른 모든 필드가 출력 문서에 반환됩니다.

{ $project: { "<field1>": 0, "<field2>": 0, ... } } // Return all but the specified fields

_id 이외의 필드를 제외하도록 지정하면 다른 $project 지정 양식을 사용할 수 없습니다. 즉, 필드를 제외하면 필드 포함을 지정하거나 기존 필드 값을 재설정하거나 새 필드를 추가할 수도 없습니다. 이 제한은 REMOVE 변수를 사용하여 필드를 조건부로 제외하는 경우에는 적용되지 않습니다.

필드를 제외하려면 $unset 단계도 참조하세요.

집계 표현식에서 변수 REMOVE(을)를 사용하여 조건부로 필드를 억제할 수 있습니다. 예시를 보려면 조건부로 필드 제외를 참조하세요.

참고

MongoDB는 문서에 새 필드를 추가할 수 있는 $addFields도 제공합니다.

새 필드를 추가하거나 기존 필드의 값을 재설정하려면 필드 이름을 지정하고 해당 값을 특정 표현식으로 설정합니다. 표현식에 대한 자세한 내용은 표현식을 참조하세요 .

필드를 리터럴로 리졸브되는 표현식으로 설정하는 대신 필드 값을 숫자 또는 부울 리터럴로 직접 설정하려면 $literal 연산자를 사용합니다. 그렇지 않으면 $project가 숫자 또는 부울 리터럴을 필드를 포함하거나 제외할 때 플래그로 처리합니다.

새 필드를 지정하고 해당 값을 기존 필드의 필드 경로로 설정하면 필드 이름을 효과적으로 변경할 수 있습니다.

$project 단계는 대괄호 [](을)를 사용해 새 배열 필드를 직접 만들 수 있도록 지원합니다. 문서에 존재하지 않는 배열 필드를 지정하는 경우, 연산은 해당 필드의 값으로 null(을)를 대체합니다. 예시는 새 배열 필드 프로젝트를 참조하세요.

단계에서는 $project 배열 인덱스 사용할 수 없습니다.

내장된 문서 내에서 필드를 프로젝션하거나 추가/재설정할 때 다음과 같이 점 표기법을 사용할 수 있습니다.

"contact.address.country": <1 or 0 or expression>

또는 필드를 중첩할 수도 있습니다:

contact: { address: { country: <1 or 0 or expression> } }

필드를 중첩할 때 내장된 문서 내에서 점 표기법을 사용하여 필드를 지정할 수 없습니다(예: contact: { "address.country": <1 or 0 or expression> }은(는) 유효하지 않습니다).

내장된 문서와 이 내장된 문서 내의 필드를 동일한 프로젝션에 모두 지정할 수는 없습니다.

다음 $project 단계는 내장된 contact 문서와 contact.address.country 필드를 모두 프로젝션하려고 시도하기 때문에 실패하며 Path collision 오류를 반환합니다.

{ $project: { contact: 1, "contact.address.country": 1 } }

이 오류는 상위 문서와 임베디드 필드가 지정된 순서와 관계없이 발생합니다. 다음 $project도 동일한 오류로 인해 실패합니다.

{ $project: { "contact.address.country": 1, contact: 1 } }

$project 단계를 사용하는 경우 이 단계는 일반적으로 파이프라인의 마지막 단계로, 클라이언트에 반환할 필드를 지정하는 데 사용됩니다.

파이프라인 의 시작 또는 중간에 $project 단계를 사용하여 후속 파이프라인 단계로 전달되는 필드 수를 줄이면 데이터베이스 이 최적화를 자동으로 수행하므로 성능이 향상되지 않을 수 있습니다.

MongoDB는 $project 단계에 빈 문서가 전달되면 오류를 반환합니다.

예를 들어 다음 파이프라인을 실행하면 오류가 발생합니다.

db.myCollection.aggregate( [ {
$project: { }
} ] )

단계에서는 $project 배열 인덱스 사용할 수 없습니다.

이 페이지의 예제에서는 sample_mflix 샘플 데이터 세트 의 데이터를 사용합니다. 이 데이터 세트를 자체 관리형 MongoDB deployment 에 로드하는 방법에 대한 자세한 내용은 샘플 데이터 세트 로드를 참조하세요. 샘플 데이터베이스를 수정한 경우 이 페이지의 예제를 실행 하려면 데이터베이스를 삭제하고 다시 만들어야 할 수 있습니다.

$project _id다음title 단계에는, 및 rated 필드만 포함됩니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project: { title: 1, rated: 1 } },
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1390f29313caabcd42e8'),
title: 'The Great Train Robbery',
rated: 'TV-G'
}
]

MongoDB _id 기본값 으로 필드 포함되어 있습니다._id 단계에서 필드 제외하려면 $project 프로젝션 _id 0 문서 에서 필드 로 설정하다 .

다음 단계에서는 필드 $project 제외하지만 _id titlerated 필드를 포함합니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project : { _id: 0, title : 1, rated : 1 } },
{ $limit: 1 }
] )
[ { title: 'The Great Train Robbery', rated: 'TV-G' } ]

다음 $project 단계에서는 출력에서 rated 필드를 제외합니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project : { "rated": 0 } },
{ $limit: 1 }
] )

또는 $unset 단계를 사용하여 필드를 제외합니다.

다음 $project 단계에서는 출력에서 imdb.idtype 필드를 제외합니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project: { "imdb.id": 0, "type": 0 } },
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1390f29313caabcd42e8'),
plot: 'A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.',
genres: [ 'Short', 'Western' ],
runtime: 11,
cast: [
'A.C. Abadie',
"Gilbert M. 'Broncho Billy' Anderson",
'George Barnes',
'Justus D. Barnes'
],
poster: 'https://m.media-amazon.com/images/M/MV5BMTU3NjE5NzYtYTYyNS00MDVmLWIwYjgtMmYwYWIxZDYyNzU2XkEyXkFqcGdeQXVyNzQzNzQxNzI@._V1_SY1000_SX677_AL_.jpg',
title: 'The Great Train Robbery',
fullplot: "Among the earliest existing films in American cinema - notable as the first film that presented a narrative story to tell - it depicts a group of cowboy outlaws who hold up a train and rob the passengers. They are then pursued by a Sheriff's posse. Several scenes have color included - all hand tinted.",
languages: [ 'English' ],
released: ISODate('1903-12-01T00:00:00.000Z'),
directors: [ 'Edwin S. Porter' ],
rated: 'TV-G',
awards: { wins: 1, nominations: 0, text: '1 win.' },
lastupdated: '2015-08-13 00:27:59.177000000',
year: 1903,
imdb: { rating: 7.4, votes: 9847 },
countries: [ 'USA' ],
tomatoes: {
viewer: { rating: 3.7, numReviews: 2559, meter: 75 },
fresh: 6,
critic: { rating: 7.6, numReviews: 6, meter: 100 },
rotten: 0,
lastUpdated: ISODate('2015-08-08T19:16:10.000Z')
},
num_mflix_comments: 0
}
]

또는 문서에 제외 사양을 중첩할 수도 있습니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project: { "imdb": { "id": 0 }, "type" : 0 } },
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1390f29313caabcd42e8'),
plot: 'A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.',
genres: [ 'Short', 'Western' ],
runtime: 11,
cast: [
'A.C. Abadie',
"Gilbert M. 'Broncho Billy' Anderson",
'George Barnes',
'Justus D. Barnes'
],
poster: 'https://m.media-amazon.com/images/M/MV5BMTU3NjE5NzYtYTYyNS00MDVmLWIwYjgtMmYwYWIxZDYyNzU2XkEyXkFqcGdeQXVyNzQzNzQxNzI@._V1_SY1000_SX677_AL_.jpg',
title: 'The Great Train Robbery',
fullplot: "Among the earliest existing films in American cinema - notable as the first film that presented a narrative story to tell - it depicts a group of cowboy outlaws who hold up a train and rob the passengers. They are then pursued by a Sheriff's posse. Several scenes have color included - all hand tinted.",
languages: [ 'English' ],
released: ISODate('1903-12-01T00:00:00.000Z'),
directors: [ 'Edwin S. Porter' ],
rated: 'TV-G',
awards: { wins: 1, nominations: 0, text: '1 win.' },
lastupdated: '2015-08-13 00:27:59.177000000',
year: 1903,
imdb: { rating: 7.4, votes: 9847 },
countries: [ 'USA' ],
tomatoes: {
viewer: { rating: 3.7, numReviews: 2559, meter: 75 },
fresh: 6,
critic: { rating: 7.6, numReviews: 6, meter: 100 },
rotten: 0,
lastUpdated: ISODate('2015-08-08T19:16:10.000Z')
},
num_mflix_comments: 0
}
]

또는 $unset 단계를 사용하여 필드를 제외합니다.

집계 표현식에서 변수 REMOVE를 사용하여 조건부로 필드를 억제할 수 있습니다.

다음 $project 단계에서는 변수를 REMOVE 사용하여 imdb.votes 필드가 와 같거나 null 빈 문자열인 경우 필드 제외합니다.

db.movies.aggregate( [
{ $match: { title: "This Is Spinal Tap" } },
{
$project: {
title: 1,
"imdb.rating": 1,
"imdb.id": 1,
"imdb.votes": {
$cond: {
if: { $in: [ "$imdb.votes", [ null, "" ] ] },
then: "$$REMOVE",
else: "$imdb.votes"
}
}
}
},
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1398f29313caabce94a3'),
title: 'This Is Spinal Tap',
imdb: { rating: 8, id: 88258 }
}
]

이 문서 의 경우 imdb.votes 이 빈 문자열이므로 MongoDB 해당 필드 출력에서 제외합니다.

$addFields와 비교

$addFields 또는 $project 단계를 사용하여 문서 필드를 제거할 수 있습니다. 파이프라인과 원본 문서를 얼마나 보존할 것인지에 따라 최적의 접근 방식이 달라질 수 있습니다.

$addFields 단계에서 $$REMOVE 사용하는 예시를 보려면 필드 제거를 참조하세요.

movies 컬렉션 의 imdb ratingvotes문서에는, 및 id 필드가 있는 내장된 문서 포함되어 있습니다.rating imdb 문서 의 필드 만 포함하려면 점 표기법 사용합니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project: { "imdb.rating": 1 } },
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1390f29313caabcd42e8'),
imdb: { rating: 7.4 }
}
]

또는 문서 에 포함 사양을 중첩합니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project: { imdb: { rating: 1 } } },
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1390f29313caabcd42e8'),
imdb: { rating: 7.4 }
}
]

다음 $project 단계에서는 leadActor 및 필드를 releaseYear 추가합니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{
$project: {
title: 1,
leadActor: { $arrayElemAt: [ "$cast", 0 ] },
releaseYear: "$year"
}
},
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1390f29313caabcd42e8'),
title: 'The Great Train Robbery',
leadActor: 'A.C. Abadie',
releaseYear: 1903
}
]

다음 작업은 yearruntime 필드를 새 myArray 필드 의 요소로 프로젝션합니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project: { myArray: [ "$year", "$runtime" ] } },
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1390f29313caabcd42e8'),
myArray: [ 1903, 11 ]
}
]

배열 사양이 문서에 존재하지 않는 필드를 포함하는 경우 해당 작업은 그 필드의 값으로 null을 대입합니다.

예를 들어 위와 동일한 문서가 주어졌을 때 다음 연산은 year, runtime 필드와 존재하지 않는 필드 $someField를 새 필드 myArray의 요소로 투영합니다.

db.movies.aggregate( [
{ $match: { title: "The Great Train Robbery" } },
{ $project: { myArray: [ "$year", "$runtime", "$someField" ] } },
{ $limit: 1 }
] )
[
{
_id: ObjectId('573a1390f29313caabcd42e8'),
myArray: [ 1903, 11, null ]
}
]

이 페이지의 C# 예제에서는 Atlas 샘플 데이터 세트sample_mflix 데이터베이스 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습하려면 MongoDB .NET/ C# 드라이버 문서에서 시작하기 를 참조하세요.

다음 MovieImdbData 클래스는 sample_mflix.movies 컬렉션 의 문서를 모델링합니다.

public class Movie
{
public ObjectId Id { get; set; }
public string Title { get; set; }
public List<string> Genres { get; set; }
public List<string> Directors { get; set; }
public List<string> Writers { get; set; }
public string Type { get; set; }
public string Plot { get; set; }
public ImdbData Imdb { get; set; }
public List<string> Cast { get; set; }
}
public class ImdbData
{
public string Id { get; set; }
public int Votes { get; set; }
public float Rating { get; set; }
}

참고

Pascal Case를 위한 ConventionPack

이 페이지의 C# 클래스는 속성 이름에 파스칼 표기법을 사용하지만, MongoDB 컬렉션의 필드 이름은 카멜 표기법을 사용합니다. 이 차이를 해결하기 위해 애플리케이션이 시작될 때 다음 코드를 사용하여 ConventionPack을 등록할 수 있습니다.

var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

MongoDB .NET/C# 드라이버를 사용하여 $project 단계를 MongoDB 집계 파이프라인에 추가하려면 PipelineDefinition 객체에서 Project() 메서드를 호출하고 ProjectionDefinitionBuilder<TDocument> 객체를 전달하세요. TDocument 클래스는 컬렉션의 문서를 나타냅니다.

다음 섹션에서는 $project 단계의 출력 문서를 사용자 지정할 수 있는 다양한 방법을 보여줍니다.

.NET/C# 드라이버를 사용할 때 특정 필드를 포함하려면 프로젝션 빌더에서 Include() 메서드를 호출하십시오. Include() 호출을 연이어 사용하여 여러 필드를 포함할 수 있습니다.

다음 코드 예제는 _id, plottitle 필드만 포함하는 문서를 생성합니다.

var pipeline = new EmptyPipelineDefinition<Movie> ()
.Project(
Builders<Movie>.Projection
.Include(m => m.Title)
.Include(m => m.Plot)
);
var result = movieCollection.Aggregate(pipeline).FirstOrDefault();

파이프라인이 다음 문서를 반환합니다.

{
"_id" : { "$oid" : "573a1390f29313caabcd42e8" },
"plot" : "A group of bandits stage a brazen train hold-up, only to find a
determined posse hot on their heels.",
"title" : "The Great Train Robbery"
}

.NET/C# 드라이버를 사용할 때 결과 문서에서 필드를 제외하려면 프로젝션 빌더에서 Exclude() 메서드를 호출하세요. 여러 필드를 제외하려면 Exclude() 호출을 연속적으로 연결(chain)해서 사용할 수 있습니다.

다음 코드 예시는 Type 필드를 제외한 문서를 생성합니다.

var pipeline = new EmptyPipelineDefinition<Movie>()
.Project(
Builders<Movie>.Projection
.Exclude(m => m.Type)
);
var result = movieCollection.Aggregate(pipeline).FirstOrDefault();

기본적으로 결과 문서에는 항상 _id 필드가 포함됩니다. 다음 코드 예시는 _id 필드를 제외하고 plottitle 필드를 포함하는 문서를 생성합니다.

var pipeline = new EmptyPipelineDefinition<Movie> ()
.Project(
Builders<Movie>.Projection
.Exclude(m => m.Id)
.Include(m => m.Title)
.Include(m => m.Plot)
);
var result = movieCollection.Aggregate(pipeline).FirstOrDefault();

파이프라인의 결과는 다음과 같은 문서입니다.

{
"plot" : "A group of bandits stage a brazen train hold-up, only to find a
determined posse hot on their heels.",
"title" : "The Great Train Robbery"
}

.NET/C# 드라이버를 사용할 때 임베디드 문서에서 필드를 제외하려면 프로젝션 빌더의 Exclude() 메서드를 호출하고 해당 클래스 속성의 경로를 전달하세요. 여러 필드를 제외하려면 Exclude() 호출을 연속적으로 연결(chain)해서 사용할 수 있습니다.

다음 코드 예시는 imdb.idtype 필드를 제외한 문서를 생성합니다.

var pipeline = new EmptyPipelineDefinition<Movie> ()
.Project(
Builders<Movie>.Projection
.Exclude("Imdb.id")
.Exclude(m => m.Type)
);
var result = movieCollection.Aggregate(pipeline).FirstOrDefault();

파이프라인 실행 결과 다음과 같은 출력이 생성됩니다.

{
"plot" : "A group of bandits stage a brazen train hold-up, only to find a
determined posse hot on their heels.",
"title" : "The Great Train Robbery",
...
"imdb" : { "rating" : 7.4000000000000004, "votes" : 9847 }
}

참고

임베디드 ID 필드에는 문자열 사용

임베디드 문서에서 ID 필드를 프로젝션하려면 필드 이름을 string으로 지정하고 Lambda 표현식은 사용하지 마세요.

집계 표현식에서 변수 REMOVE를 사용하여 조건부로 필드를 숨길 수 있습니다.

var stage = new BsonDocument
{
{ "title", 1 },
{ "imdb.id", 1 },
{ "imdb.rating", 1 },
{
"imdb.votes", new BsonDocument("$cond", new BsonDocument
{
{ "if", new BsonDocument("$eq", new BsonArray { "", "$imdb.votes" }) },
{ "then", "$$REMOVE" },
{ "else", "$imdb.votes" }
})
}
};
var pipeline = new EmptyPipelineDefinition<Movie>()
.Project(stage)
.Sample(1);
var result = movieCollection.Aggregate(pipeline).FirstOrDefault();

참고

조건부 제외를 위한 빌더가 없습니다.

이전 예제에서는 .NET/C# 드라이버가 조건부로 필드를 제외하는 빌더를 제공하지 않기 때문에 BsonDocument 객체를 사용합니다. 다른 MongoDB 언어 드라이버가 이 기능을 지원할 수도 있습니다. 자세한 내용은 MongoDB 드라이버 문서를 참조하세요.

샘플링된 문서에 imdb.votes 필드가 포함되어 있으면 파이프라인은 다음과 유사한 문서를 반환합니다.

{
"_id" : { "$oid" : "573a1390f29313caabcd42e8" },
"title" : "The Great Train Robbery",
"imdb" : { "rating" : 7.4000000000000004, "id" : 439, "votes" : 9847 }
}

imdb.votes 필드가 문서에 포함되어 있지 않으면 파이프라인은 다음과 유사한 문서를 반환합니다.

{
"_id" : { "$oid" : "573a1398f29313caabce94a3" },
"title" : "This Is Spinal Tap",
"imdb" : { "rating" : 8.0, "id" : 88258 }
}

.NET/C# 드라이버를 사용할 때 결과 문서에 계산된 필드를 포함하려면, 프로젝션 빌더의 Expression() 메서드를 호출하고 계산된 필드를 포함하는 표현식을 전달하세요. 유형 안전성을 높이기 위해 결과 문서용 모델 클래스를 다음 ProjectedMovie 클래스와 같이 정의할 수 있습니다.

public class ProjectedMovie
{
public ObjectId Id { get; set; }
public string Title { get; set; }
public string LeadActor { get; set; }
public List<string> Crew { get; set; }
}

다음 코드 예시는 여러 계산된 필드가 포함된 문서를 생성합니다.

var pipeline = new EmptyPipelineDefinition<Movie>()
.Project(
Builders<Movie>
.Projection
.Expression(m => new ProjectedMovie
{
Id = m.Id,
Title = m.Title,
LeadActor = m.Cast[0],
})
);
var result = movieCollection.Aggregate(pipeline).FirstOrDefault();

파이프라인의 결과는 다음과 같은 문서입니다.

{
"_id" : { "$oid" : "573a1390f29313caabcd42e8" },
"title" : "The Great Train Robbery",
"leadActor" : "A.C. Abadie",
...
}

.NET/C# 드라이버를 사용할 때 결과 문서에 새 배열 필드를 프로젝션하려면 프로젝션 빌더에서 Expression() 메서드를 호출하고 새 배열 필드를 포함하는 표현식을 전달하세요. 유형 안전성을 높이기 위해 결과 문서용 모델 클래스를 다음 ProjectedMovie 클래스와 같이 정의할 수 있습니다.

public class ProjectedMovie
{
public ObjectId Id { get; set; }
public string Title { get; set; }
public string LeadActor { get; set; }
public List<string> Crew { get; set; }
}

다음 코드 예시는 directorswriters 필드의 값을 포함하는 새 배열 필드 crew가 포함된 문서를 생성합니다.

var pipeline = new EmptyPipelineDefinition<Movie> ()
.Project(
Builders<Movie>
.Projection
.Expression(m => new ProjectedMovie
{
Id = m.Id,
Title = m.Title,
LeadActor = m.Cast[0],
Crew = m.Directors.Concat(m.Writers).ToList()
}
)
)
.Sample(1);
var result = movieCollection.Aggregate(pipeline).FirstOrDefault();

파이프라인은 다음과 유사한 문서를 반환합니다.

{
"_id" : { "$oid" : "573a1395f29313caabce2297" },
"title" : "The Chalk Garden",
"leadActor" : "Deborah Kerr",
"crew" : ["Ronald Neame", "John Michael Hayes (screenplay)", "Enid Bagnold (from the play by)"]
}

배열 사양에 지정된 필드가 문서에 존재하지 않을 경우, 파이프라인은 해당 필드의 값을 null로 대체합니다. 예를 들어 다음 코드 예시는 directors, writers 필드와 존재하지 않는 필드 makeupArtistscrew라는 새 필드의 요소로 생성합니다.

var stage = new BsonDocument
{
{ "crew", new BsonArray { "$directors", "$writers", "$makeupArtists" } }
};
var pipeline = new EmptyPipelineDefinition<Movie>()
.Project(stage)
.Sample(1);
var result = movieCollection.Aggregate(pipeline).FirstOrDefault();

파이프라인은 다음과 유사한 문서를 반환합니다.

{
"_id" : { "$oid" : "573a1399f29313caabced0d9" },
"crew" : [["Bill Kroyer"], ["Jim Cox (screenplay)", "Diana Young (original stories)"], null]
}

참고

빌더 클래스는 누락된 필드를 방지합니다.

앞선 예제에서는 BsonDocument 객체를 사용합니다. 이는 빌더를 사용해 배열에 누락된 필드를 추가하려 하면 .NET/C# 드라이버가 컴파일 타임 오류를 발생시키기 때문입니다. 다른 MongoDB 언어 드라이버가 이 기능을 지원할 수도 있습니다. 자세한 내용은 MongoDB 드라이버 문서를 참조하세요.

이 페이지의 Node.js 예제에서는 Atlas 샘플 데이터 세트sample_mflix 데이터베이스 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습하려면 MongoDB Node.js 운전자 설명서에서 시작하기 를 참조하세요.

MongoDB Node.js 운전자 사용하여 집계 파이프라인 에 $project 단계를 추가하려면 파이프라인 객체 에서 $project 연산자 사용합니다.

다음 섹션에서는 $project 단계의 출력 문서를 사용자 지정하는 방법을 보여 줍니다.

특정 필드를 포함하려면 $project 단계에서 필드 값을 1로 설정하세요.

다음 예제는 _id, plottitle 필드만 반환하는 문서를 생성합니다.

const pipeline = [
{
$project: {
title: 1,
plot: 1
}
}
];
const cursor = collection.aggregate(pipeline);
return cursor;

출력 문서는 다음 예시와 유사합니다.

{
_id: new ObjectId('573a1390f29313caabcd42e8'),
plot: 'A group of bandits stage a brazen train hold-up, only to find a
determined posse hot on their heels.',
title: 'The Great Train Robbery'
}

특정 필드를 제외하려면 $project 단계에서 필드의 값을 0으로 설정합니다.

다음 예시는 type 필드를 제외한 문서를 반환합니다.

const pipeline = [
{
$project: {
type: 0
}
}
];
const cursor = collection.aggregate(pipeline);
return cursor;

기본적으로 결과 문서에는 항상 _id 필드가 포함됩니다. 다음 예시는 _id 필드를 제외하고 plottitle 필드를 포함하는 문서를 반환합니다.

const pipeline = [
{
$project: {
_id: 0,
title: 1,
plot: 1
}
}
];
const cursor = collection.aggregate(pipeline);
return cursor;

출력 문서는 다음 예시와 유사합니다.

{
plot: 'A group of bandits stage a brazen train hold-up, only to find a
determined posse hot on their heels.',
title: 'The Great Train Robbery'
}

내장된 문서에서 필드를 제외하려면 $project 단계에서 해당 필드 경로의 값을 0으로 설정합니다.

참고

임베디드 필드에는 문자열 사용

임베디드 문서에서 필드를 프로젝션하려면 필드 경로를 string으로 지정하세요.

다음 예시는 imdb.idtype 필드를 제외한 문서를 반환합니다.

const pipeline = [
{
$project: {
"imdb.id": 0,
type: 0
}
}
];
const cursor = collection.aggregate(pipeline);
return cursor;

출력 문서는 다음 예시와 유사합니다.

{
plot: 'A group of bandits stage a brazen train hold-up, only to find a
determined posse hot on their heels.',
title: 'The Great Train Robbery',
imdb: { rating: 7.4000000000000004, votes: 9847 }
}

특정 필드를 조건부로 제외하려면 필드 이름에 변수 REMOVE를 포함하는 조건부 논리를 할당합니다.

const pipeline = [
{
$project: {
title: 1,
"imdb.id": 1,
"imdb.rating": 1,
"imdb.votes": {
$cond: {
if: { $eq: ["$imdb.votes", ""] },
then: "$REMOVE",
else: "$imdb.votes"
}
}
}
}
];
const cursor = collection.aggregate(pipeline);
return cursor;

문서에 imdb.votes 필드가 포함되어 있으면 파이프라인은 다음 출력 예시와 유사한 문서를 반환합니다.

{
_id: new ObjectId('573a1390f29313caabcd42e8'),
title: 'The Great Train Robbery',
imdb: { rating : 7.4000000000000004, id: 439, votes: 9847 }
}

문서에 imdb.votes 필드가 포함되어 있지 않으면 파이프라인은 다음 출력 예시와 유사한 문서를 반환합니다.

{
_id: new ObjectId('573a1390f29313caabcd42e8'),
title: 'This Is Spinal Tap',
imdb: { rating: 8.0, id: 88258 }
}

결과 문서에 계산된 필드를 포함하려면 결과를 저장하는 필드에 표현식을 할당합니다.

다음 예시는 _idtitle 필드를 동일한 이름의 새 필드로 프로젝션하고 새 필드 leadActor를 계산합니다. 그러면 해당 필드가 포함된 문서를 반환합니다.

const pipeline = [
{
$project: {
_id: "$_id",
title: "$title",
leadActor: { $arrayElemAt: ["$cast", 0] }
}
}
];
const cursor = collection.aggregate(pipeline);
return cursor;

출력 문서는 다음 예시와 유사합니다.

{
_id: new ObjectId('573a1390f29313caabcd42e8'),
title: 'The Great Train Robbery',
leadActor: 'A.C. Abadie'
}

결과 문서에 새 배열 필드를 프로젝션하려면, 배열을 저장하는 필드에 새 배열 필드를 계산하는 표현식을 할당합니다.

다음 예시는 directorswriters 필드의 값을 결합한 새 배열 필드 crew가 포함된 문서를 생성합니다.

const pipeline = [
{
$project: {
_id: "$_id",
title: "$title",
leadActor: { $arrayElemAt: ["$cast", 0] },
crew: { $concatArrays: ["$directors", "$writers"] }
}
}
];
const cursor = collection.aggregate(pipeline);
return cursor;

출력 문서는 다음 예시와 유사합니다.

{
_id: new ObjectId('573a1395f29313caabce2297'),
title: 'The Chalk Garden',
leadActor: 'Deborah Kerr',
crew: ['Ronald Neame', 'John Michael Hayes (screenplay)', 'Enid Bagnold (from the play by)']
}

배열 사양에 지정된 필드가 문서에 존재하지 않을 경우, 파이프라인은 해당 필드의 값을 null로 대체합니다. 예를 들어 다음 예시는 directors, writers 필드와 존재하지 않는 필드 makeupArtistscrew라는 새 필드의 요소로 프로젝션합니다.

const pipeline = [
{
$project: {
crew: ["$directors", "$writers", "$makeupArtists"]
}
}
];
const cursor = collection.aggregate(pipeline);
return cursor;

출력 문서는 다음 예시와 유사합니다.

{
_id: new ObjectId('573a1399f29313caabced0d9'),
crew: [['Bill Kroyer'], ['Jim Cox (screenplay)', 'Diana Young (original stories)'], null]
}

일반적인 집계 작업에 대한 추가 정보와 자세한 설명을 보려면 전체 집계 파이프라인 튜토리얼을 참조하세요.

이 페이지의 메서드에 대해 자세히 알아보려면 다음 가이드를 참조하세요.

돌아가기

$planCacheStats

이 페이지의 내용