본문으로 바로가기

저는 필요할 때 공식문서를 찾아보며 활용했는데

가장 기본이되는 명령들에 대해서 정리해봅니다.


모든 내용 출처는 공식문서입니다.

 

Aggregation Pipeline Stages — MongoDB Manual

Reference > Operators > Aggregation Pipeline Stages Aggregation Pipeline Stages In the db.collection.aggregate method and db.aggregate method, pipeline stages appear in an array. Documents pass through the stages in sequence. Stages db.collection.aggregate

docs.mongodb.com

1. $project

어떤 필드를 출력에 포함할지 제외할지 지정할 때 사용합니다.

1) 기본 형태

{ $project: { "<field1>": 1, "<field2>": 0, ... } }

 

포함할 필드에 대해서는 1 혹은 true 값을 제외할 필드에 대해서는 0 혹은 false 값을 지정합니다.

 

내장된 Document에 대해서는 아래와 같이 표현해 활용할 수 있습니다.

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

2) 예시

books 컬렉션에 아래와 같은 도큐먼트가 존재한다.

{
  "_id" : 1,
  title: "abc123",
  isbn: "0001122223334",
  author: { last: "zzz", first: "aaa" },
  copies: 5
}

위의 도큐먼트에서 _id를 제외하고 title, author 필드만 출력하려 한다면 아래와 같은 명령을 수행하면 된다.

db.books.aggregate( [ { $project : { _id: 0, title : 1 , author : 1 } } ] )

원하는 결과를 출력할 수 있다.

{ "title" : "abc123", "author" : { "last" : "zzz", "first" : "aaa" } }

2. $limit

파이프라인에서 다음 스테이지로 몇개의 도큐먼트가 넘어갈지 지정할 수 있습니다.

출력한 도큐먼트 개수를 제한할 때 사용할 수 있습니다.

1) 기본 형태

{ $limit: <positive integer> }

2) 예시

db.article.aggregate(
    { $limit : 5 }
);

 

'DB > MongoDB' 카테고리의 다른 글

[MongoDB] Aggregate Pipeline 사용 2 ( $group / $match / $sort )  (0) 2020.04.29
[MongoDB] aggregation란?  (0) 2020.04.29
[MongoDB] Mongoose란?  (0) 2020.03.19
[MongoDB] CRUD 작업하기  (0) 2020.03.19
[MongoDB] 몽고디비 시작하기  (0) 2020.03.18