본문 바로가기
Full-Stack

MONGO DB

by IT것저것 2024. 7. 9.

* 환경설정은 생략

> mongos --version 
# 몽고 DB 버전 확인하기
MONGO DB CMD
> mongod.exe 
# 몽고DB 시작
Enterprise test> use admin
switched to db admin
Enterprise admin > db.shutdownServer()
#몽고 DB 중지하기

 


몽고 DB Shell 실행하기 

 

> mongosh

 

 

몽고DB는 명령행에서 몽고 DB 인스턴스와 상호작용하는 자바스크립트 셸을 제공한다 셸은 완전한 자바스크립트 프로그램을 실행한다 
은 완전한 자바스크립트 해석기이며 임의의 자바스크립트 프로그램을 실행한다
표준 자바스크립트 라이브러리의 모든 기능을 활용할 수 있다
심지어 자바스크립트 함수를 정의하고 호출할 수도 있다
여러 줄의 명령도 작성할 수 있다. 엔터 키를 누르면 셸은 자바스크립트 구문이 완료됐는지 감지한다.
구문이 완료되지 않았으면 다음 줄에서 계속 명령어를 입력할 수 있다
엔터 키를 3회 연속 누르면 작성하던 명령을 취소하고 > 프롬프트를 반환해준다
만약 이것이 안되면 Ctrl+c를 하면 > 프롬프트를 반환해준다
화면 지우기는 
> 프롬프트에서 cls 엔터를 하면 된다
> 프롬프트에서 >.exit 하면 셸이 종료되고 운영체제 명령프롬프트로 돌아간다

 

 

 


 

몽고 DB 도큐먼트에서 사용되어지는 데이터 타입

 몽고DB에서 도큐먼트는 키와 값으로 이루어진 것들의 집합체이므로, 자바스크립트 객체와 개념적으로 닮았다는 점에서 'JSON과 닮았다' 고 할 수 있다.

도큐먼트에서 일반적으로 키는 문자열로 표현한다. 키에 매핑되어지는 데이터 값들의 타입은 다음과 같다.

1. null
 { 'key' : null } 

 2. 불리언
 { 'key' : true }
 { 'key' : fale }

 3. 숫자
 { 'key' : 100 }
 { 'key' : 3.14159 }

 { 'key' : NumberInt("100") }
 { 'key' : NumberLong("100") }

 4. 문자열
 { 'key' : "안녕하세요" }

 5. 날짜
 { 'key' : new Date() }

 6. 정규표현식
 { 'key : /정규표현식/i'}

 7. 배열
 { 'key' : ["a","b","c"]}

 8. 내장도큐먼트
 { 'key' : {"key":"데이터값"}}

 9. 객체ID
 { 'key' : ObjectId()}

 

 

📜 몽고 DB 문서 메뉴얼 📜

https://www.mongodb.com/ko-kr/docs/v6.0/tutorial/

 

MongoDB 튜토리얼 - MongoDB 매뉴얼 v6.0

 

www.mongodb.com

 

  • 도큐먼트 삽입
    • 삽입은 몽고DB에 데이터를 추가하는 기본 방법이다.
    • 도큐먼트를 삽입하려면 컬렉션의 insertOne 메소드를 사용한다.
> mongosh
Enterprise test > cls

#  cls 는 화면을 깔끔하게 지우는 명령어이다.
Enterprise test> use moviedb  
#지금은 moviedb 라는 데이터베이스가 존재하지 않기에, 선택하는 것이 아니라 moviedb 라는 데이터베이스를 생성해서 사용하겠다는 뚯이다.
switched to db moviedb



Enterprise moviedb> db
moviedb

 

 

moviedb 데이터베이스내에 존재하는 모든 컬렉션들의 이름을 조회하려면 show collections 을 하면 된다.

 

Enterprise moviedb> show collections
#결과는 아무것도 나타나지 않는다.

 

⚠️⚠️⚠️⚠️⚠️⚠️ ObjectId는 각자 pc 마다 다르므로 절대 이 코드 그대로 복붙하면 안된다 ‼️‼️‼️‼️

Enterprise moviedb> db.movies.insertOne({"title" : "해리포터"})  
# moviedb 데이터베이스내에 movies 라는 컬렉션이 없으므로 먼저 movies 라는 컬렉션을 생성해준 후 movies 컬렉션에 도큐먼트 1개를 입력해주는 것이다

# 결과
{
  acknowledged: true,
  insertedId: ObjectId("638ef047ba7f43caeda0c80a")
}

 

 

Enterprise moviedb> show collections
movies

 

 

Enterprise moviedb> db.movies.find().pretty()
# movies 컬렉션에 입력된 도큐먼트들을 조회하는 것이다.  

# 결과
[ { _id: ObjectId("638ef047ba7f43caeda0c80a"), title: '해리포터' } ]

 

 

특정 컬렉션(지금은 movies)을 삭제하려면 drop() 메소드를 사용 하면 된다. drop() 메소드를 사용하면 특정 컬렉션에 저장된 도큐먼트까지 모두 삭제된다.
Enterprise moviedb> db.movies.drop()
true

Enterprise moviedb> show collections
# 결과는 아무것도 나타나지 않는다.

 

 

여러개의 도큐먼트를 컬렉션에 삽입(대량삽입)하려면 insertMany 메소드를 사용하여 배열[]데이터베이스에 전달한다.
Enterprise moviedb> db.movies.insertMany([{"title" : "명량", "year" : 2014},
...                                       {"title" : "극한직업", "year" : 2019},
...                                       {"title" : "신과함께-죄와벌", "year" : 2017}])

# 결과
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("638ef3455f37e87f183bac5e"),
    '1': ObjectId("638ef3455f37e87f183bac5f"),
    '2': ObjectId("638ef3455f37e87f183bac60")
  }
}

Enterprise moviedb> show collections
movies

Enterprise moviedb> db.movies.find().pretty()
[
  {
    _id: ObjectId("639be753769560e7441515ab"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("639be753769560e7441515ac"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639be753769560e7441515ad"),
    title: '신과함께-죄와벌',
    year: 2017
  }
]

 

insertMany 메소드를 사용한 대량삽입시{"ordered" : false} 옵션이 있는 것과 없는 것 차이점 구분하기
- 도큐먼트를 삽입할 때 자동적으로 생성되는 _id 값을 직접 입력해서 삽입해본다.
- 도큐먼트의 _id 값은 컬렉션내에서 고유해야만 한다.
- 도큐먼트를 삽입할 때 ordered 옵션을 주지 않으면 기본은 {"ordered" : true} 가 된다.
- {"ordered" : true} 가 되면 도큐먼트의 _id 값이 중복 될 경우 오류가 발생하며 이 이후로 삽입하려고 하는 모든 도큐먼트는 삽입이 되지 않는다.

 

Enterprise moviedb> db.movies.insertMany([{"_id" : 0, "title" : "국제시장", "year" : 2014},
...                                       {"_id" : 1, "title" : "어벤저스:엔드게임", "year" : 2019},
...                                       {"_id" : 1, "title" : "겨울왕국2", "year" : 2019},
...                                       {"_id" : 2, "title" : "아바타", "year" : 2009}])

# 결과
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: movies.movies index: _id_ dup key: { _id: 1 }
Result: BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [
      WriteError {
        err: {
          index: 2,
          code: 11000,
          errmsg: 'E11000 duplicate key error collection: movies.movies index: _id_ dup key: { _id: 1 }',
          errInfo: undefined,
          op: { _id: 1, title: '겨울왕국2', year: 2019 }
        }
      }
    ],
    writeConcernErrors: [],
    insertedIds: [
      { index: 0, _id: 0 },
      { index: 1, _id: 1 },
      { index: 2, _id: 1 },
      { index: 3, _id: 2 }
    ],
    nInserted: 2,
    nUpserted: 0,
    nMatched: 0,
    nModified: 0,
    nRemoved: 0,
    upserted: []
  }
}

 

Enterprise moviedb> db.movies.find().pretty()    
#  겨울왕국2 부터 이후의 모든 도큐먼트들이 입력되지 않았음을 확인한다.


# 결과
[
  {
    _id: ObjectId("639be753769560e7441515ab"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("639be753769560e7441515ac"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639be753769560e7441515ad"),
    title: '신과함께-죄와벌',
    year: 2017
  },
  { _id: 0, title: '국제시장', year: 2014 },
  { _id: 1, title: '어벤저스:엔드게임', year: 2019 }
]

 

- 도큐먼트를 삽입할 때 자동적으로 생성되는 _id 값을 직접 입력해서 삽입해본다.
- 도큐먼트의 _id 값은 컬렉션내에서 고유해야만 한다.
- 도큐먼트를 삽입할 때 ordered 옵션을 주지 않으면 기본이 {"ordered" : true} 가 된다.
{"ordered" : false} 가 되면 도큐먼트의 _id 값이 중복 될 경우 오류가 발생하며 
  중복된 _id 값을 가지고 삽입하려고 하는 도큐먼트만 삽입이 되지 않고, 그 이후로 중복된 _id 값을 가지지 않는 도큐먼트들은 정상적으로 삽입이 된다.

 

Enterprise moviedb> db.movies.insertMany([{"_id" : 3, "title" : "베테랑", "year" : 2015},
...                                       {"_id" : 4, "title" : "괴물", "year" : 2006},
...                                       {"_id" : 4, "title" : "도둑들", "year" : 2012},
...                                       {"_id" : 5, "title" : "7번방의 선물", "year" : 2013}],
...                                       {"ordered" : false})
# 결과
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: movies.movies index: _id_ dup key: { _id: 4 }
Result: BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [
      WriteError {
        err: {
          index: 2,
          code: 11000,
          errmsg: 'E11000 duplicate key error collection: movies.movies index: _id_ dup key: { _id: 4 }',
          errInfo: undefined,
          op: { _id: 4, title: '도둑들', year: 2012 }
        }
      }
    ],
    writeConcernErrors: [],
    insertedIds: [
      { index: 0, _id: 3 },
      { index: 1, _id: 4 },
      { index: 2, _id: 4 },
      { index: 3, _id: 5 }
    ],
    nInserted: 3,
    nUpserted: 0,
    nMatched: 0,
    nModified: 0,
    nRemoved: 0,
    upserted: []
  }
}

 

Enterprise moviedb> db.movies.find().pretty() 
#도둑들 도큐먼트만 입력되지 않았고 그 이후의 7번방의 선물 도큐먼트들은 입력되었음을 확인한다.


[
  {
    _id: ObjectId("639be753769560e7441515ab"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("639be753769560e7441515ac"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639be753769560e7441515ad"),
    title: '신과함께-죄와벌',
    year: 2017
  },
  { _id: 0, title: '국제시장', year: 2014 },
  { _id: 1, title: '어벤저스:엔드게임', year: 2019 },
  { _id: 3, title: '베테랑', year: 2015 },
  { _id: 4, title: '괴물', year: 2006 },
  { _id: 5, title: '7번방의 선물', year: 2013 }
]

 

 

도큐먼트 삭제

- 이제 컬렉션(collection)에 저장되어 있는 데이터를 삭제해보자.
- 도큐먼트를 삭제하려면 deleteOne 메소드 와 deleteMany 메소드를 사용한다.
Enterprise moviedb> db.movies.deleteOne({"_id": 4})

# 결과
{ acknowledged: true, deletedCount: 1 }


Enterprise moviedb> db.movies.find().pretty()    
# "_id" 값이 4 인 도큐먼트가 삭제되었음을 확인한다.
# 결과
[
  {
    _id: ObjectId("639be753769560e7441515ab"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("639be753769560e7441515ac"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639be753769560e7441515ad"),
    title: '신과함께-죄와벌',
    year: 2017
  },
  { _id: 0, title: '국제시장', year: 2014 },
  { _id: 1, title: '어벤저스:엔드게임', year: 2019 },
  { _id: 3, title: '베테랑', year: 2015 },
  { _id: 5, title: '7번방의 선물', year: 2013 }
]
조건과 일치하는 모든 도큐먼트를 삭제하려면 deleteMany 메소드를 사용하면 된다.
Enterprise moviedb> db.movies.deleteMany({"year": 2019}) { acknowledged: true, deletedCount: 2 }
Enterprise moviedb> db.movies.find().pretty()  
# "year" 값이 2019 인 '극한직업' 과 '어벤저스:엔드게임' 도큐먼트가 삭제 되었음을 확인한다.


[
  {
    _id: ObjectId("639be753769560e7441515ab"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("639be753769560e7441515ad"),
    title: '신과함께-죄와벌',
    year: 2017
  },
  { _id: 0, title: '국제시장', year: 2014 },
  { _id: 3, title: '베테랑', year: 2015 },
  { _id: 5, title: '7번방의 선물', year: 2013 }
]
특정 컬렉션(지금은 movies)을 삭제하려면 drop() 메소드를 사용 하면 된다. drop() 메소드를 사용하면 특정 컬렉션에 저장된 도큐먼트까지 모두 삭제된다.
Enterprise moviedb> db.movies.drop()
true

Enterprise moviedb> show collections
# 결과는 아무것도 나타나지 않는다.

Enterprise moviedb> db.movies.find().pretty()
# 결과는 아무것도 나타나지 않는다.
[주의] 데이터는 한 번 삭제하면 영원히 삭제된다. 이전에 백업된 데이터가 없다라면
delete 또는 drop 되어진 도큐먼트를 복구하는 방법은 없다!!!.

 

 

도큐먼트 수정
- 도큐먼트를 데이터베이스에 저장한 후에는 updateOne, updateMany, replaceOne 메소드를 사용하여 도큐먼트를 수정한다.
   - 1개의 도큐먼트의 수정은 updateOne 를 사용하고, 여러개의 도큐먼트의 수정은 updateMany 메소드를 사용한다.
   - updateOne 메소드 및 updateMany 메소드의 첫번째 파라미터는 수정해야할 도큐먼트를 지정하는 것이고, 두번째 파라미터는 수정할 값을 지정하는 것이다.
     그런데, 만약 두번째 파라미터로 지정된 키가 존재하지 않은 경우라면 새로이 등록을 시켜준다. 즉, 이것은 마치 관계형 데이터베이스에서 컬럼을 추가해주는 효과이다.
   - replace는 replaceOne 밖에 없다. 즉, 여러 데이터를 한번에 replace 할 수는 없다는 점이 update 와 다른 점이다.
   - replace가 update 와 또 하나 다른 점은 replace 는 데이터(도큐먼트)를 완전히 변경한다는 점이다. 
     즉, update 는 해당 필드의 값만 수정하는것에 반해서, replaceOne은 기존의 데이터(도큐먼트)를 없애 버리고 완전히 새로운 데이터(도큐먼트)로 바꾸어 버린다는 것이다.
Enterprise moviedb> db.movies.insertMany([{"title" : "명량", "year" : 2014},
...                                       {"title" : "극한직업", "year" : 2019},
...                                       {"title" : "신과함께-죄와 벌", "year" : 2017},
...                                       {"title" : "국제시장", "year" : 2014},
...                                       {"title" : "어벤져스: 엔드게임", "year" : 2019},
...                                       {"title" : "겨울왕국 2", "year" : 2019},
...                                       {"title" : "아바타", "year" : 2009},
...                                       {"title" : "베테랑", "year" : 2015},
...                                       {"title" : "괴물", "year" : 2006},
...                                       {"title" : "도둑들", "year" : 2012},
...                                       {"title" : "7번방의 선물", "year" : 2013}])
# 결과
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("639c1489769560e7441515ae"),
    '1': ObjectId("639c1489769560e7441515af"),
    '2': ObjectId("639c1489769560e7441515b0"),
    '3': ObjectId("639c1489769560e7441515b1"),
    '4': ObjectId("639c1489769560e7441515b2"),
    '5': ObjectId("639c1489769560e7441515b3"),
    '6': ObjectId("639c1489769560e7441515b4"),
    '7': ObjectId("639c1489769560e7441515b5"),
    '8': ObjectId("639c1489769560e7441515b6"),
    '9': ObjectId("639c1489769560e7441515b7"),
    '10': ObjectId("639c1489769560e7441515b8")
  }
}

 

Enterprise moviedb> db.movies.find().pretty()
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515ae"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("639c1489769560e7441515af"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b0"),
    title: '신과함께-죄와 벌',
    year: 2017
  },
  {
    _id: ObjectId("639c1489769560e7441515b1"),
    title: '국제시장',
    year: 2014
  },
  {
    _id: ObjectId("639c1489769560e7441515b2"),
    title: '어벤져스: 엔드게임',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b3"),
    title: '겨울왕국 2',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b4"),
    title: '아바타',
    year: 2009
  },
  {
    _id: ObjectId("639c1489769560e7441515b5"),
    title: '베테랑',
    year: 2015
  },
  {
    _id: ObjectId("639c1489769560e7441515b6"),
    title: '괴물',
    year: 2006
  },
  {
    _id: ObjectId("639c1489769560e7441515b7"),
    title: '도둑들',
    year: 2012
  },
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '7번방의 선물',
    year: 2013
  }
]

 

 

단일 도큐먼트의 수정은 updateOne 메소드를 사용한다. 메소드의 첫번째 파라미터는 수정해야할 도큐먼트를 지정하는 것이고, 두번째 파라미터는 수정할 값을 지정하는 것이다. $set필드값을 설정한다.
# 아래의 예제는 1개 필드의 값만 변경하는 것이다.
Enterprise moviedb> db.movies.updateOne({_id: ObjectId("639c1489769560e7441515b8")}, {$set: {title: '8번방의 선물'}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find().pretty()
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515ae"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("639c1489769560e7441515af"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b0"),
    title: '신과함께-죄와 벌',
    year: 2017
  },
  {
    _id: ObjectId("639c1489769560e7441515b1"),
    title: '국제시장',
    year: 2014
  },
  {
    _id: ObjectId("639c1489769560e7441515b2"),
    title: '어벤져스: 엔드게임',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b3"),
    title: '겨울왕국 2',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b4"),
    title: '아바타',
    year: 2009
  },
  {
    _id: ObjectId("639c1489769560e7441515b5"),
    title: '베테랑',
    year: 2015
  },
  {
    _id: ObjectId("639c1489769560e7441515b6"),
    title: '괴물',
    year: 2006
  },
  {
    _id: ObjectId("639c1489769560e7441515b7"),
    title: '도둑들',
    year: 2012
  },
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '8번방의 선물',
    year: 2013
  }
]

 

 

Enterprise moviedb> db.movies.find({_id: ObjectId("639c1489769560e7441515b8")})
# 결과 
[
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '8번방의 선물',
    year: 2013
  }
]

Enterprise moviedb> db.movies.find({_id: ObjectId("639c1489769560e7441515b8")}).pretty()
[
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '8번방의 선물',
    year: 2013
  }
]

 

 

 

아래의 예제는 2개 필드의 값을 변경하는 것이다.

 

Enterprise moviedb> db.movies.updateOne({_id: ObjectId("639c1489769560e7441515b8")}, 
...                                     {$set: {title: '9번방의 선물', year: 3013}})

# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({_id: ObjectId("639c1489769560e7441515b8")}).pretty()
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '9번방의 선물',
    year: 3013
  }
]
# 아래의 예제는 2개 필드의 값을 변경하는 것이다.

Enterprise moviedb> db.movies.updateOne({_id: ObjectId("639c1489769560e7441515b8")}, 
...                                     {$set: {title: '7번방의 선물', year: 2013}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({_id: ObjectId("639c1489769560e7441515b8")})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '7번방의 선물',
    year: 2013
  }
]


Enterprise moviedb> db.movies.find({year: 2019})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515af"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b2"),
    title: '어벤져스: 엔드게임',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b3"),
    title: '겨울왕국 2',
    year: 2019
  }
]

 

 

다수의 도큐먼트의 수정은 updateMany 메소드를 사용한다.
메소드의 첫번째 파라미터는 수정해야할 도큐먼트를 지정하는 것이고,
두번째 파라미터는 수정할 값을 지정하는 것이다. $set 은 필드값을 설정한다.

 

Enterprise moviedb> db.movies.updateMany({year: 2019}, {$set: {year: 3019}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 3,
  modifiedCount: 3,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({year: 3019})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515af"),
    title: '극한직업',
    year: 3019
  },
  {
    _id: ObjectId("639c1489769560e7441515b2"),
    title: '어벤져스: 엔드게임',
    year: 3019
  },
  {
    _id: ObjectId("639c1489769560e7441515b3"),
    title: '겨울왕국 2',
    year: 3019
  }
]


Enterprise moviedb> db.movies.updateMany({year: 3019}, {$set: {year: 2019}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 3,
  modifiedCount: 3,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find({year: 2019})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515af"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b2"),
    title: '어벤져스: 엔드게임',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b3"),
    title: '겨울왕국 2',
    year: 2019
  }
]

 

replaceOne 메소드를 사용하여 해당 필드로 데이터(도큐먼트)를 완전히 바꾸어 버리기
 아래의 예제는 '겨울왕국 2' 도큐먼트를 완전히 새로운 다른 도큐먼트로 바꾸어 버리는 예제이다.
Enterprise moviedb> db.movies.replaceOne({_id: ObjectId("639c1489769560e7441515b3")}, 
...                                      {"email" : "winter@gmail.com", 
...                                       "address" : "경기도 군포시", 
...                                       "mobile" : "010-2345-6789"})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find({_id: ObjectId("639c1489769560e7441515b3")})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515b3"),
    email: 'winter@gmail.com',
    address: '경기도 군포시',
    mobile: '010-2345-6789'
  }
]


Enterprise moviedb> db.movies.find().pretty()
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515ae"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("639c1489769560e7441515af"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b0"),
    title: '신과함께-죄와 벌',
    year: 2017
  },
  {
    _id: ObjectId("639c1489769560e7441515b1"),
    title: '국제시장',
    year: 2014
  },
  {
    _id: ObjectId("639c1489769560e7441515b2"),
    title: '어벤져스: 엔드게임',
    year: 2019
  },
  {
    _id: ObjectId("639c1489769560e7441515b3"),
    email: 'winter@gmail.com',
    address: '경기도 군포시',
    mobile: '010-2345-6789'
  },
  {
    _id: ObjectId("639c1489769560e7441515b4"),
    title: '아바타',
    year: 2009
  },
  {
    _id: ObjectId("639c1489769560e7441515b5"),
    title: '베테랑',
    year: 2015
  },
  {
    _id: ObjectId("639c1489769560e7441515b6"),
    title: '괴물',
    year: 2006
  },
  {
    _id: ObjectId("639c1489769560e7441515b7"),
    title: '도둑들',
    year: 2012
  },
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '7번방의 선물',
    year: 2013
  }
]


Enterprise moviedb> db.movies.replaceOne({_id: ObjectId("639c1489769560e7441515b3")}, 
...                                      {"title" : "겨울왕국 2", "year" : 2019})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find({_id: ObjectId("639c1489769560e7441515b3")})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515b3"),
    title: '겨울왕국 2',
    year: 2019
  }
]

 

 

 

증가 와 감소 숫자값을 증감 할때 사용하는 $inc 를 사용하여 이미 존재하는 키의 값(숫자값만 가능함)을 누적하여 증가시키거나 감소시킬때 사용한다. 만약에 존재하는 키가 없는 경우라면 키를 새로이 등록을 시켜준다. $inc 는 int, long, double, decimal 타입 값에만 사용가능하다.
null, 불리언, 문자열 타입의 데이터값 에는 사용이 불가하다. 
# 다음은 관객수(attendance)라는 키를 넣어서 값을 누적 시키거나 감소 시켜 보겠다.

# 아래의 예제는 attendance 키가 없으므로 새로이 등록을 시켜주며, 값은 10000 으로 되어진다. 
Enterprise moviedb> db.movies.updateOne({title: '7번방의 선물', year: 2013}, {$inc: {attendance: 10000}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find({title: '7번방의 선물', year: 2013})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '7번방의 선물',
    year: 2013,
    attendance: 10000
  }
]

 

 

# 아래의 예제는 attendance 키가 있으므로 attendance 값은 기존의 값인 10000 에 20000 이 증가된 30000 이 되어진다.

Enterprise moviedb> db.movies.updateOne({title: '7번방의 선물', year: 2013}, {$inc: {attendance: 20000}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find({title: '7번방의 선물', year: 2013})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '7번방의 선물',
    year: 2013,
    attendance: 30000
  }
]

 

 

# 아래의 예제는 attendance 키가 있으므로 attendance 값은 기존의 값인 30000 에 -5000 이 증가된 25000 이 되어진다.


Enterprise moviedb> db.movies.updateOne({title: '7번방의 선물', year: 2013}, {$inc: {attendance: -5000}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find({title: '7번방의 선물', year: 2013})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '7번방의 선물',
    year: 2013,
    attendance: 25000
  }
]

 

 

특정 필드(컬럼)만 삭제하기 -- 특정 필드(컬럼)만 삭제하려면 updateOne 메소드에 $unset 을 사용하면 특정 필드(컬럼)만 삭제 된다.
Enterprise moviedb> db.movies.updateOne({title: '7번방의 선물', year: 2013}, {$unset: {attendance: 25000}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({title: '7번방의 선물', year: 2013})
# 결과
[
  {
    _id: ObjectId("639c1489769560e7441515b8"),
    title: '7번방의 선물',
    year: 2013
  }
]

 

여러개의 도큐먼드에 존재하는 특정 필드(컬럼)만 삭제하기 -- 여러개의 도큐먼드에 존재하는 특정 필드(컬럼)만 삭제하려면 updateMany 메소드에 $unset 을 사용하면 특정 필드(컬럼)만 삭제 된다.
# 아래의 예제는 '괴물' 과 '도둑들' 2개의 도큐먼트에 attendance 라는 숫자가 증감이 되어지는 키를 넣는 것이다. 
Enterprise moviedb> db.movies.updateOne({title: '괴물', year: 2006}, {$inc: {attendance: 5000}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.updateOne({title: '도둑들', year: 2012}, {$inc: {attendance: 7000}})
# 결과
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find().pretty()
# 결과
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    attendance: 5000
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    attendance: 7000
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013
  }
]

 

 

✔️ 문법 ✔️

 

db.collection.update(
  { 'columnName': { '$exists': true } }, // 일치하는 컬럼, 필드를 찾기
  { '$unset': { 'columnName': true } },  // $unset 연산자로 제거하기
  false, // [Option] Upsert 적용 여부 <Boolean> upsert 는 update + insert 의 합성어로서 수정할 대상이 없다라면 insert 동작을 수행해주는 것이다.
  true   // [Option] 멀티 업데이트(Multi update) 여부 <Boolean>
)
아래의 예제는 movies 컬렉션에 저장된 도큐먼트 중에 attendance 라는 필드(==키, ==컬럼)를 가지고 있는 도큐먼트에서 attendance 라는 필드(==키, ==컬럼)를 삭제하는 예제이다. 
Enterprise moviedb> db.movies.updateMany({"attendance": {"$exists":true}}, 
                                         {"$unset": {"attendance": true}}, 
					 false, 
					 true)
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 2,
  modifiedCount: 2,
  upsertedCount: 0
}

 

 

Enterprise moviedb> db.movies.find().pretty() 

#  '괴물' 과 '도둑들' 2개의 도큐먼트에 추가해 두었던 attendance 라는 필드(==키, ==컬럼)가 삭제되었음을 확인한다.  
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013
  }
]

   

 

 

✔️ 배열 ✔️

- 배열을 다루는데 있어서 updateOne() 메소드와 updateMany() 메소드가 사용되어진다

※>>> 배열에 요소 추가하기 <<<
※ $push 는 배열이 이미 존재할 경우라면 배열 끝에 요소를 추가해주는 것이고, 배열이 존재하지 않는 경우라면 새로운 배열을 생성해주는 것이다.
moviedb 데이터베이스의 movies 컬렉션에 존재하는 도큐먼트에 reviews 라는 키(필드,컬럼)를 삽입하여 이것을 배열로 사용하도록 해보겠다.

 

Enterprise moviedb> db.movies.updateMany({}, {$push : {"reviews" : {"name" : "이순신", "comment" : "좋아요"}}})

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 11,
  modifiedCount: 11,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find().pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  }
]

Enterprise moviedb> db.movies.updateMany({}, {$push : {"reviews" : {"name" : "엄정화", "comment" : "감동이에요"}}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 11,
  modifiedCount: 11,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find().pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]


Enterprise moviedb> db.movies.updateOne({title:'7번방의 선물', year:2013},
...                                     {$push : {"reviews" : {"name" : "유관순", "comment" : "추천해요"}}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}


Enterprise moviedb> db.movies.find().pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '유관순', comment: '추천해요' }
    ]
  }
]

     

 

※ >>>> $push 에 $each 를 사용하면 한번 작업으로 여러개를 추가할 수 있게 된다. <<<< ※
Enterprise moviedb> db.movies.updateOne({ title: '7번방의 선물', year: 2013 }, 
... {$push : {"reviews" : {$each : 
...                                [ {"name":"한석규", "comment":"넘좋아요"}, 
...                                  {"name":"두석규", "comment":"넘넘좋아요"}, 
...                                  {"name":"세석규", "comment":"넘넘넘좋아요"},
...                                  {"name":"이미자", "comment":"후후후"}
...                                ]}}})
# 결과 
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find().pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '유관순', comment: '추천해요' },
      { name: '한석규', comment: '넘좋아요' },
      { name: '두석규', comment: '넘넘좋아요' },
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '이미자', comment: '후후후' }
    ]
  }
]


Enterprise moviedb> db.movies.find({title : '7번방의 선물'}).pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '유관순', comment: '추천해요' },
      { name: '한석규', comment: '넘좋아요' },
      { name: '두석규', comment: '넘넘좋아요' },
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '이미자', comment: '후후후' }
    ]
  }
]
※ >>>> 배열의 크기를 정하려면 $push 에 $slice 를 사용하면 된다. <<<< ※ 
===> 아래의 예제는 배열에 추가할 수 있는 크기를 10개 정한 것이다. 그러므로 배열 요소의 개수가 10개 까지만 허용된다. 

※ >>>> 배열속에 데이터를 입력한 후 배열 요소를 정렬하고자 할 경우에는 $sort 를 사용하면 된다. <<<< ※ 
===> 아래의 예제는 배열속에 데이터를 입력한 후, 배열 요소를 name 키의 데이터 값을 기준으로 내림차순 정렬한 것이다.

 

 

 

Enterprise moviedb> db.movies.updateOne({ title: '7번방의 선물', year: 2013 }, 
... {$push : {"reviews" : {$each : 
...                                [ {"name":"일지매", "comment":"또 보고싶어오"}, 
...                                  {"name":"이지매", "comment":"두번 봤어요"}, 
...                                  {"name":"삼지매", "comment":"세번 봤어요"},
...                                  {"name":"사지매", "comment":"네번 봤어요"},
...                                  {"name":"오지매", "comment":"다섯번 봤어요"},
...                                  {"name":"육지매", "comment":"여섯번 봤어요"}
...                                ],
...                        $slice : -10,
...                        $sort : {"name" : -1} 
...                       }}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({title : '7번방의 선물'}).pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '이미자', comment: '후후후' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '삼지매', comment: '세번 봤어요' },
      { name: '사지매', comment: '네번 봤어요' },
      { name: '두석규', comment: '넘넘좋아요' }
    ]
  }
]

 

#아래의 예제는 배열속에 데이터를 입력한 후, 배열 요소를 name 키의 데이터 값을 기준으로 오름차순 정렬한 것이다. 
Enterprise moviedb> db.movies.updateOne({ title: '7번방의 선물', year: 2013 },
... {$push : {"reviews" : {$each :
...                               [ {"name":"서영학", "comment":"하하"},
...                                 {"name":"조용필", "comment":"호호호"}
...                               ],
...                        $slice : -11,
...                        $sort : {"name" : 1}
...                       }}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({title : '7번방의 선물'}).pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '사지매', comment: '네번 봤어요' },
      { name: '삼지매', comment: '세번 봤어요' },
      { name: '서영학', comment: '하하' },
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' },
      { name: '조용필', comment: '호호호' }
    ]
  }
]

 

 

※>>> 배열에 요소 삭제하기 <<<※ 
--- $pull 은 지정된 조건에 맞는 배열 요소를 제거하는데 사용된다.

 

Enterprise moviedb> db.movies.updateOne({"title" : "7번방의 선물"},
...                                     {$pull : {"reviews" : {"name" : "사지매"} } } )
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({title : '7번방의 선물'}).pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '삼지매', comment: '세번 봤어요' },
      { name: '서영학', comment: '하하' },
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' },
      { name: '조용필', comment: '호호호' }
    ]
  }
]

 

※>>> 배열에 요소 삭제하기 <<<※ 
---  $pop 은 배열의 맨끝 요소 또는 맨앞의 요소를 제거하는데 사용된다.
===> {$pop : {"키명" : 1}} 은 배열의 마지막 요소를 제거하는 것이고, 
     {$pop : {"키명" : -1}} 은 배열의 맨 처음 요소를 제거하는 것이다.
Enterprise moviedb> db.movies.updateOne({"title" : "7번방의 선물"}, {$pop : {"reviews" : 1} } )
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({title : '7번방의 선물'}).pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '삼지매', comment: '세번 봤어요' },
      { name: '서영학', comment: '하하' },
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]

Enterprise moviedb> db.movies.updateOne({"title" : "7번방의 선물"}, {$pop : {"reviews" : -1} } )
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({title : '7번방의 선물'}).pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '서영학', comment: '하하' },
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]


Enterprise moviedb> db.movies.updateOne({"title" : "7번방의 선물"}, {$pop : {"reviews" : -1} } )
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Enterprise moviedb> db.movies.find({title : '7번방의 선물'}).pretty()
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]


Enterprise movies> .exit

 

 

 

 ➡️ 쿼리

몽고DB 에서 쿼리는 find() 함수를 사용한다 

 

C:\Users\user1>mongosh

Enterprise test> use moviedb
switched to db moviedb

Enterprise moviedb> db
moviedb

 

※ >>>> 데이터를 조회하고자 할 경우에는 find() 함수를 사용하면 된다. <<<< ※ 
==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 모든 도큐먼트들을 조회하는 것이다.

 

Enterprise moviedb> db.movies.find()
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]

 

※ >>>> find() 함수 속에 {}을 넣으면 모든 document 를 의미한다. <<<< ※ 
==> 아래의 예제도 moviedb 데이터베이스의 movies 컬렉션에 저장된 모든 도큐먼트들을 조회하는 것이다.
Enterprise moviedb> db.movies.find({})
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]
※ >>>> 데이터를 정렬해서 조회하고자 할 경우에는 find()에 sort() 를 사용하면 된다.

 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 도큐먼트들을 title 키의 데이터 값을 기준으로 오름차순 정렬한 것이다.
Enterprise moviedb> db.movies.find().sort({"title" : 1})

또는

Enterprise moviedb> db.movies.find().sort( {title : 1} )
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7e"),
    title: 'Mission Imposible',
    year: null
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7d"),
    title: '아바타2-물의길',
    year: 2022
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]

 

아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 도큐먼트들을 title 키의 데이터 값을 기준으로 내림차순 정렬한 것이다.

Enterprise moviedb> db.movies.find().sort( {"title" : -1} )

또는 

Enterprise moviedb> db.movies.find().sort( {title : -1} )
[
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7d"),
    title: '아바타2-물의길',
    year: 2022
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7e"),
    title: 'Mission Imposible',
    year: null
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]

 

※ >>>> 첫번째 요소만 보려면 findOne() 함수를 사용하면 된다. <<<< ※ 
===> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 첫번째 도큐먼트를 조회해온 것이다.


Enterprise moviedb> db.movies.findOne()
{
  _id: ObjectId("6403094702f58c7349c30765"),
  title: '명량',
  year: 2014,
  reviews: [
    { name: '이순신', comment: '좋아요' },
    { name: '엄정화', comment: '감동이에요' }
  ]
}

 

※ >>>> find() 함수에 조건을 넣어서 사용할 수 있다.  <<<< ※ 
==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 도큐먼트들 중 "year" 키값이 2014 인 도큐먼트를 조회하는 것이다.

Enterprise moviedb> db.movies.find({"year" : 2014})
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]
※ >>>> AND 쿼리는 , 를 사용하면 된다. find() 함수에 조건을 넣어서 사용할 때 , 를 사용하여 여러조건을 넣으면 AND 쿼리가 된다.  <<<< ※ 
==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 도큐먼트들 중 "year" 키값이 2014 이면서 "title" 키값이 "국제시장" 인 도큐먼트를 조회하는 것이다.


Enterprise moviedb> db.movies.find({"year" : 2014, "title" : "국제시장"})
[
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]

 

 

※ >>>> find() 함수를 사용하여 조회할 때 출력하고자 하는 데이터를 선별할 수 있다.  <<<< ※ 
==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 모든 도큐먼트들을 조회하는데 "title" 과 "year" 키의 값만 조회하는 것이다. 
    "_id" 키는 지정하지 않아도 무조건 항상 출력되어진다.
    
    
    Enterprise moviedb> db.movies.find({}, {"title" : 1, "year" : 1} )
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013
  }
]
 >>>> find() 함수를 사용하여 조회할 때 조회하고자 하는 데이터 조건 및 출력하고자 하는 데이터를 선별할 수 있다.  <<<< ※ 
==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2014 이면서 "title" 키값이 "국제시장" 인 도큐먼트들을 조회하는데 
    "title" 과 "year" 키의 값만 조회하는 것이다. 
    "_id" 키는 지정하지 않아도 무조건 항상 출력되어진다.
    
    Enterprise moviedb> db.movies.find({"year" : 2014, "title" : "국제시장"}, {"title" : 1, "year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014
  }
]

 

 

 >>>> find() 함수를 사용하여 조회할 때 출력시키고 싶은 않은 데이터를 선별할 수 있다.  <<<< ※ 
==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2014 이면서 "title" 키값이 "국제시장" 인 도큐먼트들을 조회하는데 
    "reviews" 키의 값을 제외한 나머지 모든 키와 값들을 조회하는 것이다. 

Enterprise moviedb> db.movies.find({"year" : 2014, "title" : "국제시장"}, {"reviews" : 0})
[
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014
  }
]

 

 

>>>> find() 함수를 사용하여 조회할 때 출력시키고 싶은 않은 데이터를 선별할 수 있다.  <<<< ※ 
==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2014 이면서 "title" 키값이 "국제시장" 인 도큐먼트들을 조회하는데 
    "_id" 키의 값을 제외한 나머지 모든 키와 값들을 조회하는 것이다.
    
    Enterprise moviedb> db.movies.find({"year" : 2014, "title" : "국제시장"}, {"_id" : 0})
[
  {
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]

 

 

 find() 함수를 사용하여 조회할 때 출력시키고 싶은 않은 데이터를 선별할 수 있다.  <<<< ※ 
==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2014 이면서 "title" 키값이 "국제시장" 인 도큐먼트들을 조회하는데 
    "_id" 키와 값은 제외하고 "reviews" 키와 값들만 조회하는 것이다. 
    
    Enterprise moviedb> db.movies.find({"year" : 2014, "title" : "국제시장"}, {"_id" : 0, "reviews" : 1})
[
  {
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]

 

 

※ >>>> ========== 범위 조건절을 사용하여 데이터를 조회할 수 있다. 수치 뿐 아니라 문자열도 범위 검색이 가능하다. ========== <<<< ※

< 은 "$lt" <= 은 "$lte" > 은 "$gt" >= 은 "$gte" 이다.
아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2019 미만인 것을, 키값이 _id 와 키값이 reviews 를 제외하고 조회하는 것이다. 

Enterprise moviedb> db.movies.find({"year" : {$lt : 2019} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '명량', year: 2014 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '국제시장', year: 2014 },
  { title: '아바타', year: 2009 },
  { title: '베테랑', year: 2015 },
  { title: '괴물', year: 2006 },
  { title: '도둑들', year: 2012 },
  { title: '7번방의 선물', year: 2013 }
]

 

 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2019 이하인 것을, 키값이 _id 와 키값이 reviews 를 제외하고 조회하는 것이다
 
 Enterprise moviedb> db.movies.find({"year" : {$lte : 2019} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '명량', year: 2014 },
  { title: '극한직업', year: 2019 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '국제시장', year: 2014 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 },
  { title: '아바타', year: 2009 },
  { title: '베테랑', year: 2015 },
  { title: '괴물', year: 2006 },
  { title: '도둑들', year: 2012 },
  { title: '7번방의 선물', year: 2013 }
]



==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2014 보다 큰 것을, 키값이 _id 와 키값이 reviews 를 제외하고 조회하는 것이다. 
Enterprise moviedb> db.movies.find({"year" : {$gt : 2014} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '극한직업', year: 2019 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 },
  { title: '베테랑', year: 2015 }
]


==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2014 이상인 것을, 키값이 _id 와 키값이 reviews 를 제외하고 조회하는 것이다. 
Enterprise moviedb> db.movies.find({"year" : {$gte : 2014} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '명량', year: 2014 },
  { title: '극한직업', year: 2019 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '국제시장', year: 2014 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 },
  { title: '베테랑', year: 2015 }
]


==> 아래의 예제는 moviedb 데이터베이스의 movies 컬렉션에 저장된 "year" 키값이 2014 부터 2017 까지인 것을, 키값이 _id 와 키값이 reviews 를 제외하고 조회하는 것이다. 
Enterprise moviedb> db.movies.find({"year" : {$gte : 2014 , $lte : 2017} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '명량', year: 2014 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '국제시장', year: 2014 },
  { title: '베테랑', year: 2015 }
]

 

 

※ >>>> "not equal" 을 나타내는 것이 $ne 이다. $ne 는 모든 데이터형에서 사용되어진다.  <<<< ※ 

===> 아래의 예제는 "year" 키값이 2014 가 아닌 것을 조회하는 것이다. 
Enterprise moviedb> db.movies.find({"year" : {$ne : 2014} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '극한직업', year: 2019 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 },
  { title: '아바타', year: 2009 },
  { title: '베테랑', year: 2015 },
  { title: '괴물', year: 2006 },
  { title: '도둑들', year: 2012 },
  { title: '7번방의 선물', year: 2013 }
]



===> 아래의 예제는 "title" 키값이 "극한직업" 이 아닌 것을 조회하는 것이다.
Enterprise moviedb> db.movies.find({"title" : {$ne : "극한직업"} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '명량', year: 2014 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '국제시장', year: 2014 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 },
  { title: '아바타', year: 2009 },
  { title: '베테랑', year: 2015 },
  { title: '괴물', year: 2006 },
  { title: '도둑들', year: 2012 },
  { title: '7번방의 선물', year: 2013 }
]

 

 

※ >>>> OR 쿼리는 $in 과 $or 를 사용한다. <<<< ※
===> 아래의 예제는 "year" 키값이 2014 또는 2017 또는 2019 인 것을 조회하는 것이다.
Enterprise moviedb> db.movies.find({"year" : {$in : [2014, 2017, 2019]} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '명량', year: 2014 },
  { title: '극한직업', year: 2019 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '국제시장', year: 2014 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 }
]



===> 아래의 예제는 "title" 키값이 "명량" 또는 "극한직업" 또는 "국제시장" 인 것을 조회하는 것이다.
Enterprise moviedb> db.movies.find({"title" : {$in : ["명량","극한직업","국제시장"]} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '명량', year: 2014 },
  { title: '극한직업', year: 2019 },
  { title: '국제시장', year: 2014 }
]

 

※ >>>> $in 의 부정이 $nin 이다. <<<< ※
===> 아래의 예제는 "year" 키값이 2014 또는 2017 또는 2019 가 아닌 것을 조회하는 것이다.
Enterprise moviedb> db.movies.find({"year" : {$nin : [2014, 2017, 2019]} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '아바타', year: 2009 },
  { title: '베테랑', year: 2015 },
  { title: '괴물', year: 2006 },
  { title: '도둑들', year: 2012 },
  { title: '7번방의 선물', year: 2013 }
]


===> 아래의 예제는 "title" 키값이 "명량" 또는 "극한직업" 또는 "국제시장" 이 아닌 것을 조회하는 것이다.
Enterprise moviedb> db.movies.find({"title" : {$nin : ["명량","극한직업","국제시장"]} }, {"_id" : 0, "reviews" : 0} )
[
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 },
  { title: '아바타', year: 2009 },
  { title: '베테랑', year: 2015 },
  { title: '괴물', year: 2006 },
  { title: '도둑들', year: 2012 },
  { title: '7번방의 선물', year: 2013 }
]

 

 

※ >>>> 서로 다른 조건절을 사용할때는 $or 를 사용하여 나타낸다. <<<< ※
===> 아래의 예제는 "title" 키값이 "아바타" 이거나 "year" 키값이 2014 또는 2017 또는 2019 인 도큐먼트를 조회하는 것이다.
Enterprise moviedb> db.movies.find({$or : [ {"title" : "아바타"}, {"year" : {$in : [2014, 2017, 2019]} } ] } , {"_id" : 0, "reviews" : 0} )
[
  { title: '명량', year: 2014 },
  { title: '극한직업', year: 2019 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '국제시장', year: 2014 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 },
  { title: '아바타', year: 2009 }
]

 

 

※ >>>> **** null 검색하기 와 존재하지 않는 키 검색하기 **** <<<< ※
Enterprise moviedb> db.movies.insertMany([{"title" : "아바타2-물의길", "year" : 2022},
...                                       {"title" : "Mission Imposible", "year":null}])


===> 아래의 예제는 "year" 키값이 null 인 도큐먼트를 조회하는 것인데, "_id" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "year": null }, { "_id": 0})
[ { title: 'Mission Imposible', year: null } ]


===> 아래의 예제는 "year" 키값이 null 인 도큐먼트를 조회하는 것인데, "_id" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "year":  {$eq : null, $exists : true} }, { "_id": 0})
[ { title: 'Mission Imposible', year: null } ]


===> 아래의 예제는 "year" 키값이 null 이 아닌 도큐먼트를 조회하는 것인데 "_id" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "year": {$ne : null} }, { "_id": 0, "reviews":0})
[
  { title: '명량', year: 2014 },
  { title: '극한직업', year: 2019 },
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '국제시장', year: 2014 },
  { title: '어벤져스: 엔드게임', year: 2019 },
  { title: '겨울왕국 2', year: 2019 },
  { title: '아바타', year: 2009 },
  { title: '베테랑', year: 2015 },
  { title: '괴물', year: 2006 },
  { title: '도둑들', year: 2012 },
  { title: '7번방의 선물', year: 2013 },
  { title: '아바타2-물의길', year: 2022 }
]


===> 아래의 예제는 "reviews" 키값이 존재하는 도큐먼트를 조회하는 것인데, "_id" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "reviews":  {$exists : true} }, { "_id": 0})
[
  {
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]


===> 아래의 예제는 "reviews" 키값이 존재하지 않는 도큐먼트를 조회하는 것인데, "_id" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "reviews":  {$exists : false} }, { "_id": 0})
[
  { title: '아바타2-물의길', year: 2022 },
  { title: 'Mission Imposible', year: null }
]

 

 

정규표현식을 사용하여 도큐먼트 검색하기
===> 아래의 예제는 "title" 키값이 대소문자 구분 없이 시작 글자가 'mission' 으로 시작하는 도큐먼트를 조회하는 것인데, "_id" 키 값과 "reviews" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "title": /^mission.*/i}, { "_id": 0, "reviews": 0 })
[ { title: 'Mission Imposible', year: null } ]


===> 아래의 예제는 "title" 키값이 시작 글자가 '아바타' 로 시작하는 도큐먼트를 조회하는 것인데, "_id" 키 값과 "reviews" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "title": /^아바타.*/}, { "_id": 0, "reviews": 0 })
[ { title: '아바타', year: 2009 }, { title: '아바타2-물의길', year: 2022 } ]


===> 아래의 예제는 "title" 키값이 '물' 이 들어가 있는 도큐먼트를 조회하는 것인데, "_id" 키 값과 "reviews" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "title": /.*물.*/}, { "_id": 0, "reviews": 0 })
[
  { title: '괴물', year: 2006 },
  { title: '7번방의 선물', year: 2013 },
  { title: '아바타2-물의길', year: 2022 }
]


===> 아래의 예제는 "title" 키값이 '물' 이 들어가 있는 도큐먼트를 조회하는 것인데, "_id" 키 값과 "reviews" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "title": /물/}, { "_id": 0, "reviews": 0 })
[
  { title: '괴물', year: 2006 },
  { title: '7번방의 선물', year: 2013 },
  { title: '아바타2-물의길', year: 2022 }
]


===> 아래의 예제는 "title" 키값이 '-' 가 들어가 있는 도큐먼트를 조회하는 것인데, "_id" 키 값과 "reviews" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "title": /.*\-.*/}, { "_id": 0, "reviews": 0 })
[
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '아바타2-물의길', year: 2022 }
]


===> 아래의 예제는 "title" 키값이 '-' 가 들어가 있는 도큐먼트를 조회하는 것인데, "_id" 키 값과 "reviews" 키 값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({ "title": /\-/}, { "_id": 0, "reviews": 0 })
[
  { title: '신과함께-죄와 벌', year: 2017 },
  { title: '아바타2-물의길', year: 2022 }
]

 

 

 

※ >>>> **** AND 와 OR 를 같이 쓸 수 있다. **** <<<< ※
===> 아래의 예제는 "year" 키 값이 2015 이상을 가지는 도큐먼트 중에서 "title" 키 값이 아바타로 시작하거나 "reviews" 키가 존재하는 도큐먼트를 조회하는 것인데, 조회할 때 "_id" 키의 값은 출력하지 않는다.
Enterprise moviedb> db.movies.find( { "year" : {$gte : 2015} , $or : [{"title" : /^아바타.*/} , {"reviews" : {$exists : true}}] } , {"_id" : 0} )
[
  {
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  { title: '아바타2-물의길', year: 2022 }
]




===> 아래의 예제는 "year" 키 값이 2015 이상을 가지는 도큐먼트 중에서 "title" 키 값이 아바타로 시작하거나 "reviews" 키가 존재하는 도큐먼트를 조회하는 것인데, 조회할 때 "_id" 키의 값은 출력하지 않고 "year" 키값을 기준으로 오름차순 정렬하여 나타낸다. 
Enterprise moviedb> db.movies.find( { "year" : {$gte : 2015} , $or : [{"title" : /^아바타.*/} , {"reviews" : {$exists : true}}] } , {"_id" : 0} ).sort({"year" : 1})
[
  {
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  { title: '아바타2-물의길', year: 2022 }

 

 

※ >>>> ===> **** 배열을 검색하기 **** <==== <<<< ※
===> 아래는 모든 배열의 요소가 정확하게 일치하는 도큐먼트만을 가져오는 것이다.
Enterprise moviedb> db.movies.find({"reviews" : [{"name": "이순신", "comment": "좋아요" }, {"name": "엄정화", "comment": "감동이에요" }]})
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]



===> 아래는 일치한 것이 없으므로 결과물이 아무것도 나오지 않는다.  
Enterprise moviedb> db.movies.find({"reviews" : [{"name": "이순신", "comment": "좋아요" }] })



===> 아래는 일치한 것이 없으므로(순서가 일치하지 않으므로) 결과물이 아무것도 나오지 않는다.
Enterprise moviedb> db.movies.find({"reviews" : [{"name": "엄정화", "comment": "감동이에요" }, {"name": "이순신", "comment": "좋아요" }] })

 

 

※ **** 배열의 요소를 검색할 때 전체 배열의 요소와 완전히 일치하는 것이 아니라, 배열의 요소 중 몇개만 일치하는 도큐먼트를 검색할 경우 $all 을 사용하여 쿼리해온다. **** ※
===> 아래는 $all 을 사용하여 검색 조건에 입력된 배열의 요소가 포함되어진 도큐먼들을 조회해오는 것이다.  
Enterprise moviedb> db.movies.find({"reviews" : {$all : [{"name": "이순신", "comment": "좋아요" }] } })
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]



===> 아래는 $all 을 사용하여 검색 조건에 입력된 배열의 요소가 포함되어진 도큐먼트들을 조회해오는 것이다.  
Enterprise moviedb> db.movies.find({"reviews" : {$all : [{"name": "엄정화", "comment": "감동이에요"}, 
...                                                      {"name": "이순신", "comment": "좋아요"}] 
...                                             } } )
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]



===> 아래는 $all 을 사용하여 검색 조건에 입력된 배열의 요소가 포함되어진 도큐먼트들을 조회해오는 것이다. 
Enterprise moviedb> db.movies.find({"reviews" : {$all : [ {"name": "유관순", "comment": "추천해요"} ] } } )
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]

 

 

※ >>>> $size 를 사용하여 배열의 크기 숫자와 일치하는 도큐먼트들을 조회해온다. <<<< ※
===> 아래는 $size 를 사용하여 "reviews" 키의 데이터값은 배열로 되어져 있는데 그 배열의 크기가 2인 도큐먼트들을 조회해오는 것인데, "_id" 키 데이터값은 제외한다는 것이다.
Enterprise moviedb> db.movies.find({"reviews" : {$size : 2} }, {"_id" : 0} )
[
  {
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]



===> 아래는 $size 를 사용하여 배열의 크기 숫자와 일치하는 도큐먼트들을 조회해오는 것이다.
===> !!! 그런데 조심할 것은 $size 는 다른 $조건절과 결합해서 사용할 수 없다는 것이다. 예를 들어 $size 는 $gt 와 결합하여 사용할 수 없다. !!! 
Enterprise moviedb> db.movies.find({"reviews" : {$size : 7} }, {"_id" : 0} )
[
  {
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  }
]

===> 아래는 $size 에 다른 $조건절과 결합하여 사용하였기에 오류가 발생하는 것이다.
Enterprise moviedb> db.movies.find({"reviews" : {$size : {$gte:2}} }, {"_id" : 0} )
MongoServerError: Failed to parse $size. Expected a number in: $size: { $gte: 2 }

 

 

※ >>>> 배열 요소중 일부분을 가져오고자 할때는 $slice 를 사용하면 된다. <<<< ※ ===> find() 함수의 첫번째 파라미터는 추출하고자 하는 조건이고, ===> find() 함수의 두번째 파라미터에 $slice 를 사용하여 배열에서 가져오고자 하는 배열요소를 지정해주면 된다.
===> 아래 예제는 모든 도큐먼트들에서 "reviews" 키값이 배열로 되어져 있는데 배열의 요소중 첫번째 입력된 배열요소만 가져오는데 "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다. 
     출력결과를 보면 "reviews" 가 존재하지 않는 'Mission Imposible' 과 '아바타2-물의길' 도 나타난다. "reviews" 가 존재하는 경우 첫번째 입력된 배열요소만 가져오는 것이다. 
Enterprise moviedb> db.movies.find({}, {"reviews" : {$slice : 1}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7e"),
    title: 'Mission Imposible',
    year: null
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [ { name: '세석규', comment: '넘넘넘좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7d"),
    title: '아바타2-물의길',
    year: 2022
  }
]



===> 아래 예제는 "year" 키값이 2013 부터 2017 까지 그리고 2022 인 도큐먼트들에서 "reviews" 키값이 배열로 되어져 있는데 이 배열의 요소중 첫번째 입력된 배열요소만 가져오는데 "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다. 
     출력결과를 보면 "reviews" 가 존재하지 않는 '아바타2-물의길' 도 나타난다. "reviews" 가 존재하는 경우 첫번째 입력된 배열요소만 가져오는 것이다. 
Enterprise moviedb> db.movies.find({"year" : {$in : [2013, 2014, 2015, 2016, 2017, 2022]} }, {"reviews" : {$slice : 1}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [ { name: '세석규', comment: '넘넘넘좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7d"),
    title: '아바타2-물의길',
    year: 2022
  }
]



===> 아래 예제는 "year" 키값이 2013 부터 2017 까지 그리고 2022 인 도큐먼트들 중 "reviews" 키가 존재하는 도큐먼트 에서 "reviews" 키값이 배열로 되어져 있는데 배열의 요소중 첫번째 입력된 배열요소만 가져오는데 "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다.  
     출력결과를 보면 "reviews" 가 존재하지 않는 '아바타2-물의길' 은 나타나지 않는다.  
Enterprise moviedb> db.movies.find({"year" : {$in : [2013, 2014, 2015, 2016, 2017, 2022]}, "reviews" : {$exists : true}}, {"reviews" : {$slice : 1}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [ { name: '세석규', comment: '넘넘넘좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  }
]



===> 아래 예제는 "year" 키값이 2013 부터 2017 까지 그리고 2022 인 도큐먼트들 중 "reviews" 키가 존재하는 도큐먼트 에서 "reviews" 키값이 배열로 되어져 있는데 배열의 요소중 첫번째 배열요소 와 두번째 배열요소 2개만 가져오는데 "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다.  
Enterprise moviedb> db.movies.find({"year" : {$in : [2013, 2014, 2015, 2016, 2017, 2022]}, "reviews" : {$exists : true}}, {"reviews" : {$slice : 2}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]



===> 아래 예제는 "year" 키값이 2013 부터 2017 까지 그리고 2022 인 도큐먼트들 중 "reviews" 키가 존재하는 도큐먼트 에서 "reviews" 키값이 배열로 되어져 있는데 배열의 요소중 첫번째 배열요소 와 두번째 배열요소 와 세번째 배열요소 3개만 가져오는데 "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다.  
Enterprise moviedb> db.movies.find({"year" : {$in : [2013, 2014, 2015, 2016, 2017, 2022]}, "reviews" : {$exists : true}}, {"reviews" : {$slice : 3}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]



===> 아래 예제는 "year" 키값이 2013 부터 2017 까지 그리고 2022 인 도큐먼트들 중 "reviews" 키가 존재하는 도큐먼트 에서 "reviews" 키값이 배열로 되어져 있는데 배열의 요소중 맨 아래의 배열요소 1개만 가져오는데 "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다.  
Enterprise moviedb> db.movies.find({"year" : {$in : [2013, 2014, 2015, 2016, 2017, 2022]}, "reviews" : {$exists : true}}, {"reviews" : {$slice : -1}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [ { name: '이순신', comment: '좋아요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [ { name: '엄정화', comment: '감동이에요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [ { name: '엄정화', comment: '감동이에요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [ { name: '엄정화', comment: '감동이에요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [ { name: '엄정화', comment: '감동이에요' } ]
  }
]



===> 아래 예제는 "year" 키값이 2013 부터 2017 까지 그리고 2022 인 도큐먼트들 중 "reviews" 키가 존재하는 도큐먼트 에서 "reviews" 키값이 배열로 되어져 있는데 배열의 요소중 맨 아래의 배열요소 3개만 가져오는데 "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다.  
Enterprise moviedb> db.movies.find({"year" : {$in : [2013, 2014, 2015, 2016, 2017, 2022]}, "reviews" : {$exists : true}}, {"reviews" : {$slice : -3}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]



===> 아래 예제는 "year" 키값이 2013 부터 2017 까지 그리고 2022 인 도큐먼트들 중 "reviews" 키가 존재하는 도큐먼트 에서 "reviews" 키값이 배열로 되어져 있는데 배열의 요소중 배열의 인덱스 번호가 1 부터 4개 요소만 가져오는데, "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다.  
Enterprise moviedb> db.movies.find({"year" : {$in : [2013, 2014, 2015, 2016, 2017, 2022]}, "reviews" : {$exists : true}}, {"reviews" : {$slice : [1,4]}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [ { name: '엄정화', comment: '감동이에요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [ { name: '엄정화', comment: '감동이에요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [ { name: '엄정화', comment: '감동이에요' } ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [ { name: '엄정화', comment: '감동이에요' } ]
  }
]



===> 아래 예제는 "year" 키값이 2013 부터 2017 까지 그리고 2022 인 도큐먼트들 중 "reviews" 키가 존재하는 도큐먼트 에서 "reviews" 키값이 배열로 되어져 있는데 배열의 요소중 배열의 인덱스 번호가 2 부터 4개 요소만 가져오는데, "year" 키값을 기준으로 오름차순 정렬하여 나타내주는 것이다.  
Enterprise moviedb> db.movies.find({"year" : {$in : [2013, 2014, 2015, 2016, 2017, 2022]}, "reviews" : {$exists : true}}, {"reviews" : {$slice : [2,4]}}).sort({"year" : 1})
[
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: []
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: []
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: []
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: []
  }
]

 

 

※ >>>> 다중의 결과물에서 보고 싶은 결과물의 개수를 제한 하려면 limit()함수를 사용한다. <<<< ※
Enterprise moviedb> db.movies.find({}).limit(2)
[
  {
    _id: ObjectId("6403094702f58c7349c30765"),
    title: '명량',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]

 

 

※ >>>> 다중의 결과물에서 보고 싶지 않은 결과물은 skip()함수를 사용하여 건너 띌수 있다. <<<< ※
Enterprise moviedb> db.movies.find({}).skip(1)
[
  {
    _id: ObjectId("6403094702f58c7349c30766"),
    title: '극한직업',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7d"),
    title: '아바타2-물의길',
    year: 2022
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7e"),
    title: 'Mission Imposible',
    year: null
  }
]




Enterprise moviedb> db.movies.find({}).skip(2)
[
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076a"),
    title: '겨울왕국 2',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076b"),
    title: '아바타',
    year: 2009,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076c"),
    title: '베테랑',
    year: 2015,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076d"),
    title: '괴물',
    year: 2006,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076e"),
    title: '도둑들',
    year: 2012,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c3076f"),
    title: '7번방의 선물',
    year: 2013,
    reviews: [
      { name: '세석규', comment: '넘넘넘좋아요' },
      { name: '엄정화', comment: '감동이에요' },
      { name: '오지매', comment: '다섯번 봤어요' },
      { name: '유관순', comment: '추천해요' },
      { name: '육지매', comment: '여섯번 봤어요' },
      { name: '이미자', comment: '후후후' },
      { name: '이순신', comment: '좋아요' }
    ]
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7d"),
    title: '아바타2-물의길',
    year: 2022
  },
  {
    _id: ObjectId("6608d8e9ec537ab6da72ae7e"),
    title: 'Mission Imposible',
    year: null
  }
]



Enterprise moviedb> db.movies.find({}).skip(2).limit(3)
[
  {
    _id: ObjectId("6403094702f58c7349c30767"),
    title: '신과함께-죄와 벌',
    year: 2017,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30768"),
    title: '국제시장',
    year: 2014,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  },
  {
    _id: ObjectId("6403094702f58c7349c30769"),
    title: '어벤져스: 엔드게임',
    year: 2019,
    reviews: [
      { name: '이순신', comment: '좋아요' },
      { name: '엄정화', comment: '감동이에요' }
    ]
  }
]

 

 

>>> 집계 프레임워크(aggregation framework) 란? <<<
MongoDB 에서는 일반적으로 데이터를 추출하고자 할때 find() 메소드를 사용한다. 하지만 컬렉션에 있는 수 많은 도큐먼트의 데이터를 다양한 방식으로 결합해서 새로운 정보를 추출하고자 할 때는 find() 메소드만 사용하기에는 한계가 있다. 그래서 이것을 해결해주는 것이 MongoDB의 고급 쿼리 언어인 집계 프레임워크(aggregation framework) 이다. 한마디로, 집계 프레임워크(aggregation framework)는 컬렉션에 있는 수 많은 도큐먼트의 데이터를 다양한 방식으로 결합해서 새로운 데이터를 만드는 MongoDB의 고급 쿼리 언어이다.
>>> 집계(aggregation)란? ==> 컬렉션에 저장된 방대한 양의 도큐먼트들을 여러 단계를 거쳐 처리하는 방법을 말하는 것이다.
>>> 집계 프레임워크(aggregation framework)는 "파이프라인" 개념을 기반으로 한다.
==> "파이프라인" 이란? 데이터 처리를 여러 단계로 나누어 처리하는 방식이며, 각 단계에서 입력 데이터를 처리하여 출력 데이터를 만들어 다음 단계로 전달하는 것이다. "파이프라인" 에는 대표적으로 일치(match), 선출(projection), 정렬(sort), 건너뛰기(skip), 제한(limit) 단계가 있다.

 

※ db.컬렉션명.aggregate(....) ==> SQL 명령어의 FROM 에 해당한다.

============================================================================================
 Aggregation Operators          설명
============================================================================================
※ $match     ==> 처리될 도큐먼트를 선택하는 것이다. find()메소드와 비슷한 역할을 수행한다.
                 SQL 명령어의 WHERE 및 HAVING 에 해당한다. 

※ $group     ==> 입력으로주어진 도큐먼트를 지정된 조건에 맞게 그룹핑해서 카운트나 합계또는 평균 등의 계산을 처리한다.    
                 SQL 명령어의 GROUP BY 에 해당한다.

※ $project   ==> 도큐먼트에서 선출(출력)할 또는 선출(출력)안할 필드를 지정한다.  
                 SQL 명령어의 SELECT 에 해당한다.

※ $sort      ==> 도큐먼트를 정렬한다.                
                 SQL 명령어의 ORDER BY 에 해당한다.

※ $unwind    ==> 입력 도큐먼트가 배열로 구성된 필드를 가지고 있으며, 이를 여러 도큐먼트로 풀어서 다음 스테이지로 전달한다.  
                 예를들어, 입력 도큐먼트가 10개의 엘리먼트를 가진 배열로 구성된 필드를 가진다면 $unwind 스테이지는 이를 10개의 도큐먼트로 만들어서 다음 스테이지로 전달한다.
                 마치 SQL 명령어의 CROSS JOIN 에 해당한다.
         
※ $count     ==> 주어진 입력 도큐먼의 개수를 세어서 다음 스테이지로 전달한다.

※ $out       ==> 파이프라인의 결과(출력)를 컬렉션에 쓴다.

※ $limit     ==> 입력으로 주어진 도큐먼트에서 지정된 수의 도큐먼트만 다음 스테이지로 전달한다.
                 SQL 명령어의 LIMIT 에 해당한다.

※ $skip      ==> 입력으로 주어진 도큐먼트에서 지정된 수의 도큐먼트는 건너뛰고, 나머지 도큐먼트만 다음 스테이지로 전달한다.

※ $redact    ==> 도큐먼트의 각 필드 또는 서브 도큐먼트의 포맷이 다양한 경우에, 지정된 형태의 포맷과 일치하는 서브 도큐먼트 또는 필드만으로 도큐먼트를 재구성한다.

※ $lookup    ==> 주어진 입력 도큐먼트와 다른 컬렉션( 동일 데이터베이스 내의 컬렉션 )과 레프트 아우터( LEFT OUTER )조인을 실행해서 결과를 다음 스테이지로 전달한다.

※ $geoNear   ==> 주어진 위치를 기준으로 위치 기반의 검색을 수행해서 일정 반경 이내의 결과만 다음 스테이지로 전달

※ $addFields ==> 입력으로 주어진 도큐먼트에 새로운 필드를 추가한다.


====================================================================================
SQL Terms, Functions, and Concepts        MongoDB Aggregation Operators
====================================================================================
WHERE                                     $match
GROUP BY                                  $group
HAVING                                    $match
SELECT                                    $project
ORDER BY                                  $sort
LIMIT                                     $limit
SUM()                                     $sum
COUNT()                                   $sum
                                          $sortByCount
join                                      $lookup
SELECT INTO NEW_TABLE                     $out
MERGE INTO TABLE                          $merge (Available starting in MongoDB 4.2)
UNION ALL                                 $unionWith
=====================================================================================

 

 

>>> ==== 집계 쿼리를 작성하는 방법의 예 ==== <<<
db.컬렉션명.aggregate(pipeline, options)

 pipeline ==> 집계 단계가 포함된 배열이다.
 options  ==> 선택적 매개변수 집계

 pipeline ==> [
                { $match : { … } },
                { $group : { … } },
                { $sort : { … } }
              ]
※ 집계 쿼리 사용을 위해서 'universitydb' 라는 데이터베이스를 만들고 여기에 두 개의 컬렉션을 만들어 사용하겠다. 
  첫 번째 컬렉션은 'universities' 이다.(데이터는 실제가 아님)
  두 번째 컬렉션은 'courses' 이다.

C:\Users\user1>mongosh

Enterprise test> use universitydb
switched to db universitydb

Enterprise universitydb> db
universitydb

Enterprise universitydb> db.universities.insertMany([
	{
	  country : 'Spain',
	  city : 'Salamanca',
	  name : 'USAL',
	  location : {
	    type : 'Point',
	    coordinates : [ -5.6722512,17, 40.9607792 ]
	  },
	  students : [
	    { year : 2014, number : 24774 },
	    { year : 2015, number : 23166 },
	    { year : 2016, number : 21913 },
	    { year : 2017, number : 21715 }
	  ]
	},
	{
	  country : 'Spain',
	  city : 'Salamanca',
	  name : 'UPSA',
	  location : {
	    type : 'Point',
	    coordinates : [ -5.6691191,17, 40.9631732 ]
	  },
	  students : [
	    { year : 2014, number : 4788 },
	    { year : 2015, number : 4821 },
	    { year : 2016, number : 6550 },
	    { year : 2017, number : 6125 }
	  ]
	}
   ])


Enterprise universitydb> db.universities.find().pretty()
[
  {
    _id: ObjectId("661b9e1ee93865b1f48af61c"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: [
      { year: 2014, number: 24774 },
      { year: 2015, number: 23166 },
      { year: 2016, number: 21913 },
      { year: 2017, number: 21715 }
    ]
  },
  {
    _id: ObjectId("661b9e1ee93865b1f48af61d"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'UPSA',
    location: { type: 'Point', coordinates: [ -5.6691191, 17, 40.9631732 ] },
    students: [
      { year: 2014, number: 4788 },
      { year: 2015, number: 4821 },
      { year: 2016, number: 6550 },
      { year: 2017, number: 6125 }
    ]
  }
]



Enterprise universitydb> db.courses.insertMany([
	{
	  university : 'USAL',
	  name : 'Computer Science',
	  level : 'Excellent'
	},
	{
	  university : 'USAL',
	  name : 'Electronics',
	  level : 'Intermediate'
	},
	{
	  university : 'USAL',
	  name : 'Communication',
	  level : 'Excellent'
	}
  ])



Enterprise universitydb> db.courses.find().pretty()
[
  {
    _id: ObjectId("661ba0e2e93865b1f48af61e"),
    university: 'USAL',
    name: 'Computer Science',
    level: 'Excellent'
  },
  {
    _id: ObjectId("661ba0e2e93865b1f48af61f"),
    university: 'USAL',
    name: 'Electronics',
    level: 'Intermediate'
  },
  {
    _id: ObjectId("661ba0e2e93865b1f48af620"),
    university: 'USAL',
    name: 'Communication',
    level: 'Excellent'
  }
]
※ >>> $match 예제 <<< ※

Enterprise universitydb> db.universities.aggregate([
      {$match : {country : 'Spain', city : 'Salamanca'}}
    ]).pretty()

>> 출력결과 <<
[
  {
    _id: ObjectId("661b9e1ee93865b1f48af61c"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: [
      { year: 2014, number: 24774 },
      { year: 2015, number: 23166 },
      { year: 2016, number: 21913 },
      { year: 2017, number: 21715 }
    ]
  },
  {
    _id: ObjectId("661b9e1ee93865b1f48af61d"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'UPSA',
    location: { type: 'Point', coordinates: [ -5.6691191, 17, 40.9631732 ] },
    students: [
      { year: 2014, number: 4788 },
      { year: 2015, number: 4821 },
      { year: 2016, number: 6550 },
      { year: 2017, number: 6125 }
    ]
  }
]
※ >>> $project 예제 <<< ※

==> 도큐먼트에 있는 모든 필드를 검색해야 하는 경우는 거의 없다. 필요 이상의 데이터를 처리하지 않도록 필요한 필드만 반환하는 것이 좋다.

$project 단계를 사용하여 이 작업을 수행하고 필요한 계산된 필드를 추가합니다.
이 예제에서는 country, city , name 필드만 필요하다.

Enterprise universitydb> db.universities.aggregate([
      {$project : {country : 1, city : 1, name : 1 }}
   ]).pretty()

>> 출력결과를 보면 아래와 같이 _id 필드는 무조건 출력이 되어진다.<<
[
  {
    _id: ObjectId("661b9e1ee93865b1f48af61c"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL'
  },
  {
    _id: ObjectId("661b9e1ee93865b1f48af61d"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'UPSA'
  }
]


>> country, city , name 필드만 필요로 하므로 _id : 0 을 사용하여 _id 필드는 출력되지 않도록 한다. <<
Enterprise universitydb> db.universities.aggregate([
      {$project : {_id : 0, country : 1, city : 1, name : 1 }}
   ]).pretty()

[
  { country: 'Spain', city: 'Salamanca', name: 'USAL' },
  { country: 'Spain', city: 'Salamanca', name: 'UPSA' }
]
※ >>> $match  및  $project  예제 <<< ※

Enterprise universitydb> db.universities.aggregate([
      {$match : {country : 'Spain', city : 'Salamanca', name: 'USAL' }},
      {$project : {_id : 0, country : 1, city : 1, name : 1,  location: 1 }}
    ]).pretty()

[
  {
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] }
  }
]
※ >>> $group 예제 <<< ※

==> $group 스테이지(단계)를 사용하여 개수, 합계, 평균 ,최대값, 최소값 찾기와 같이 필요한 모든 집계 또는 요약 쿼리를 수행할 수 있다.


※ >>> $group 및 $sum 예제 <<< ※
>>> 아래는 $sum 을 사용하여 courses 컬렉션에서 level 별 도큐먼트의 개수를 구하는 것이다.

마치 아래의 SQL 구문과 같은 뜻이다. 
select level, count(*) AS totaldocs 
from courses
group by level;

Enterprise universitydb> db.courses.aggregate([
      {$group : {_id : '$level', totaldocs : {$sum : 1 }}}
   ]).pretty()

>> 출력결과 <<
[
  { _id: 'Excellent', totaldocs: 2 },
  { _id: 'Intermediate', totaldocs: 1 }
]


>>>>  _id 에 '$level' 을 주었다. 이것이 바로 level 필드 값으로 그룹화를 하겠다는 것이기 때문이다. <<<<
>>>>  $sum 연산자를 사용하여 입력된 각 도큐먼트 마다 totaldocs 라는 가상의 필드에 1 을 주어서 모두 더한 값으로 이와같은 방식으로 도큐먼트의 개수를 알아온다.

>>> $group 스테이지(단계) 에서는 아래에 보이는 연산자를 사용하여 요약통계를 제공해준다.
----------------------------------------------------------------------------
연산자    의미
----------------------------------------------------------------------------
$count    지정된 그룹에 있는 도큐먼트 개수를 계산한다.
$max    각 그룹의 필드 최대값
$min    각 그룹의 필드 최소값
$avg    숫자 타입의 필드 평균을 계산한다.
$sum    숫자 타입의 필드 합계를 계산한다. 만약 도큐먼트의 개수가 필요하다면 필드의 값 대신 1을 사용한다.
$push    각 그룹에 속한 모든 도큐먼트의 필드 값을 배열로 반환한다. 중복값이 포함될 수 있다.
$addToSet  각 그룹에 속한 모든 도큐먼트의 필드 값 중에서 유니크한 값을 배열로 반환한다. 중복값이 포함될 수 없다.
$first     각 그룹의 첫 번째 값을 반환한다. 선행조건으로 먼저 $sort 를 실행한 다음에 해야 한다.
$last      각 그룹의 마지막 값을 반환한다. 선행조건으로 먼저 $sort 를 실행한 다음에 해야 한다. 
----------------------------------------------------------------------------

※ >>> $group 및 $sort 예제 <<< ※

마치 아래의 SQL 구문과 같은 뜻이다. 
select level, count(*) AS totaldocs 
from courses
group by level
order by totaldocs asc;

Enterprise universitydb> db.courses.aggregate([
      {$group : {_id : '$level', totaldocs : {$sum : 1 }}},
      {$sort : {totaldocs : 1}} 
   ]).pretty()

>> 출력결과 <<
[
  { _id: 'Intermediate', totaldocs: 1 },
  { _id: 'Excellent', totaldocs: 2 }
]



※ >>> $match 및 $count 예제 <<< ※

$count 는 {$count : "문자열"} 형식으로 사용되어진다.

Enterprise universitydb> db.scores.insertMany([
	{ "_id" : 1, "subject" : "국어", "score" : 88 },
        { "_id" : 2, "subject" : "국어", "score" : 92 },
        { "_id" : 3, "subject" : "국어", "score" : 97 },
        { "_id" : 4, "subject" : "국어", "score" : 71 },
        { "_id" : 5, "subject" : "국어", "score" : 79 },
        { "_id" : 6, "subject" : "국어", "score" : 83 },
	{ "_id" : 7, "subject" : "수학", "score" : 63 },
	{ "_id" : 8, "subject" : "수학", "score" : 85 },
	{ "_id" : 9, "subject" : "수학", "score" : 98 },
	{ "_id" : 10, "subject" : "수학", "score" : 75 }
   ])

>> 실행결과 <<
{
  acknowledged: true,
  insertedIds: {
    '0': 1,
    '1': 2,
    '2': 3,
    '3': 4,
    '4': 5,
    '5': 6,
    '6': 7,
    '7': 8,
    '8': 9,
    '9': 10
  }
}


Enterprise universitydb> db.scores.find().pretty()

>> 출력결과 <<
[
  { _id: 1, subject: '국어', score: 88 },
  { _id: 2, subject: '국어', score: 92 },
  { _id: 3, subject: '국어', score: 97 },
  { _id: 4, subject: '국어', score: 71 },
  { _id: 5, subject: '국어', score: 79 },
  { _id: 6, subject: '국어', score: 83 },
  { _id: 7, subject: '수학', score: 63 },
  { _id: 8, subject: '수학', score: 85 },
  { _id: 9, subject: '수학', score: 98 },
  { _id: 10, subject: '수학', score: 75 }
]



Enterprise universitydb> db.scores.aggregate([])

>> 출력결과 <<
[
  { _id: 1, subject: '국어', score: 88 },
  { _id: 2, subject: '국어', score: 92 },
  { _id: 3, subject: '국어', score: 97 },
  { _id: 4, subject: '국어', score: 71 },
  { _id: 5, subject: '국어', score: 79 },
  { _id: 6, subject: '국어', score: 83 },
  { _id: 7, subject: '수학', score: 63 },
  { _id: 8, subject: '수학', score: 85 },
  { _id: 9, subject: '수학', score: 98 },
  { _id: 10, subject: '수학', score: 75 }
]



Enterprise universitydb> db.scores.aggregate([
      {$match : {score : {$gte : 80} } },
      {$count: "합격자명수"}
  ]).pretty()

>> 출력결과 <<
[ { '합격자명수': 6 } ]

==> 첫번째 단계로 score 필드값이 80 이상인 도큐먼트만 가져온다. 
==> 이결과물을 두번째 단계로 넘기는데 두번째 단계에서는 그 도큐먼트의 개수를 출력해주는데 "합격자명수" 라는 필드로 보여주겠다는 말이다.



Enterprise universitydb> db.scores.aggregate([
      {$match : {subject : '수학', score : {$gte : 70} } },
      {$count: "수학합격자명수"}
  ]).pretty()

>> 출력결과 <<
[ { '수학합격자명수': 3 } ]



Enterprise universitydb> db.scores.aggregate([
      {$match : {subject : '국어', score : {$gte : 90} } },
      {$count: "국어합격자명수"}
  ]).pretty()

>> 출력결과 <<
[ { '국어합격자명수': 2 } ]
[ { _id: null, doccnt: 10 } ]



Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : '$subject', totaldocs : {$count : {}} } }
   ]).pretty()

마치 아래의 SQL 구문과 같은 뜻이다. 
select subject, count(*) AS totaldocs 
from scores
group by subject;

>> 출력결과 <<
[ { _id: '수학', totaldocs: 4 }, { _id: '국어', totaldocs: 6 } ]



Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : '$subject', totaldocs : {$count : {}} } },
      {$sort : {totaldocs : -1}}
   ]).pretty()

마치 아래의 SQL 구문과 같은 뜻이다. 
select subject, count(*) AS totaldocs 
from scores
group by subject
order by totaldocs desc;

>> 출력결과 <<
[ { _id: '국어', totaldocs: 6 }, { _id: '수학', totaldocs: 4 } ]


>>> 아래는 $count 를 사용하여 courses 컬렉션에서 level 별 도큐먼트의 개수를 구하는 것이다.

마치 아래의 SQL 구문과 같은 뜻이다. 
select level, count(*) AS totaldocs 
from courses
group by level;

Enterprise universitydb> db.courses.aggregate([
      {$group : {_id : '$level', totaldocs : {$count : {} }}},
      {$sort : {totaldocs : -1}}
   ]).pretty()

>> 출력결과 <<
[
  { _id: 'Excellent', totaldocs: 2 },
  { _id: 'Intermediate', totaldocs: 1 }
]




※ >>> $group 및 $sum 예제 <<< ※

Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : null, totalscore : {$sum : '$score'} } }
  ]).pretty()

>> 출력결과 <<
[ { _id: null, totalscore: 831 } ]


Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : '$subject', totalscore : {$sum : '$score'} } },
      {$sort : {_id : 1}}
  ]).pretty()

>> 출력결과 <<
[ { _id: '국어', totalscore: 510 }, { _id: '수학', totalscore: 321 } ]



※ >>> $group 및 $avg 예제 <<< ※

Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : null, avgscore : {$avg : '$score'} } }
  ]).pretty()

>> 출력결과 <<
[ { _id: null, avgscore: 83.1 } ]


Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : '$subject', avgscore : {$avg : '$score'} } },
      {$sort : {avgscore : -1}}
  ]).pretty()

>> 출력결과 <<
[ { _id: '국어', avgscore: 85 }, { _id: '수학', avgscore: 80.25 } ]



※ >>> $group 및 $max 예제 <<< ※

Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : null, maxscore : {$max : '$score'} } }
  ]).pretty()

>> 출력결과 <<
[ { _id: null, maxscore: 98 } ]


Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : '$subject', maxscore : {$max : '$score'} } },
      {$sort : {maxscore : -1}}
  ]).pretty()

>> 출력결과 <<
[ { _id: '수학', maxscore: 98 }, { _id: '국어', maxscore: 97 } ]



※ >>> $group 및 $min 예제 <<< ※

Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : null, minscore : {$min : '$score'} } }
  ]).pretty()

>> 출력결과 <<
[ { _id: null, minscore: 63 } ]


Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : '$subject', minscore : {$min : '$score'} } },
      {$sort : {minscore : 1}}
  ]).pretty()

>> 출력결과 <<
[ { _id: '수학', minscore: 63 }, { _id: '국어', minscore: 71 } ]


 
※ >>> $group 및 $first 예제 <<< ※

Enterprise universitydb> db.scores.aggregate([
      {$sort : {score : -1}},
      {$group : {_id : null, firstscore : {$first : '$score'} } }
  ]).pretty()

>> 출력결과 <<
[ { _id: null, firstscore: 98 } ]


Enterprise universitydb> db.scores.aggregate([
      {$sort : {score : -1}},
      {$group : {_id : '$subject', firstscore : {$first : '$score'} } }
  ]).pretty()

>> 출력결과 <<
[ { _id: '수학', firstscore: 98 }, { _id: '국어', firstscore: 97 } ]



※ >>> $group 및 $last 예제 <<< ※

Enterprise universitydb> db.scores.aggregate([
      {$sort : {score : -1}},
      {$group : {_id : null, lastscore : {$last : '$score'} } }
  ]).pretty()

>> 출력결과 <<
[ { _id: null, lastscore: 63 } ]


Enterprise universitydb> db.scores.aggregate([
      {$sort : {score : -1}},
      {$group : {_id : '$subject', lastscore : {$last : '$score'} } }
  ]).pretty()

>> 출력결과 <<
[ { _id: '수학', lastscore: 63 }, { _id: '국어', lastscore: 71 } ]






※ >>> $match 및  $group 및 $count 예제 <<< ※

Enterprise universitydb> db.scores.aggregate([
      {$match : {score : {$gte : 80} } },
      {$group : {_id : '$subject', totaldocs : {$count : {}} } },
      {$sort : {totaldocs : -1}}
   ]).pretty()

>> 출력결과 <<
[ { _id: '국어', totaldocs: 4 }, { _id: '수학', totaldocs: 2 } ]


마치 아래의 SQL 구문과 같은 뜻이다. 
select subject, count(*) AS totaldocs 
from scores
where score >= 80
group by subject
order by totaldocs desc;



※ >>> $match 및  $group 및 $avg 예제 <<< ※

Enterprise universitydb> db.scores.aggregate([
      {$match : {score : {$gte : 80} } },
      {$group : {_id : '$subject', scoreavg : {$avg : '$score'} } },
      {$sort : {scoreavg : -1}}
   ]).pretty()

>> 출력결과 <<
[ { _id: '수학', scoreavg: 91.5 }, { _id: '국어', scoreavg: 90 } ]


마치 아래의 SQL 구문과 같은 뜻이다. 
select subject, avg(score) AS scoreavg 
from scores
where score >= 80
group by subject
order by scoreavg desc;





※ >>> !!!!!!! 배열속에 있는 데이터 $group 예제 !!!!!!! <<< ※

Enterprise universitydb> db.universities.find().pretty()

>> 출력결과 <<
[
  {
    _id: ObjectId("661b9e1ee93865b1f48af61c"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: [
      { year: 2014, number: 24774 },
      { year: 2015, number: 23166 },
      { year: 2016, number: 21913 },
      { year: 2017, number: 21715 }
    ]
  },
  {
    _id: ObjectId("661b9e1ee93865b1f48af61d"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'UPSA',
    location: { type: 'Point', coordinates: [ -5.6691191, 17, 40.9631732 ] },
    students: [
      { year: 2014, number: 4788 },
      { year: 2015, number: 4821 },
      { year: 2016, number: 6550 },
      { year: 2017, number: 6125 }
    ]
  }
]



Enterprise universitydb> db.universities.aggregate([]).pretty()

>> 출력결과 <<
[
  {
    _id: ObjectId("668bae621e45930dc3c4d28a"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: [
      { year: 2014, number: 24774 },
      { year: 2015, number: 23166 },
      { year: 2016, number: 21913 },
      { year: 2017, number: 21715 }
    ]
  },
  {
    _id: ObjectId("668bae621e45930dc3c4d28b"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'UPSA',
    location: { type: 'Point', coordinates: [ -5.6691191, 17, 40.9631732 ] },
    students: [
      { year: 2014, number: 4788 },
      { year: 2015, number: 4821 },
      { year: 2016, number: 6550 },
      { year: 2017, number: 6125 }
    ]
  }
]



※ >>> name 별로 students 의 number 합계 구하기 예제 1 <<< ※

Enterprise universitydb> db.universities.find({},
	{ _id : 0, 
	 name : 1,
	 total_students_number : {$sum : "$students.number"}
        }).sort({total_students_number : -1})

>> 출력결과 <<
[
  { name: 'USAL', total_students_number: 91568 },
  { name: 'UPSA', total_students_number: 22284 }
]



※ >>> 1개 도큐먼트 students 의 number 합계 구하기 예제 1 <<< ※

Enterprise universitydb> db.universities.find({country : 'Spain', city : 'Salamanca', name : 'UPSA'},
	{ _id : 0, 
	 name : 1,
	 total_students_number : {$sum: "$students.number"}
        })

>> 출력결과 <<
[ { name: 'UPSA', total_students_number: 22284 } ]



※ >>> name 별로 students 의 number 합계 구하기 예제 2 <<< ※

Enterprise universitydb> db.universities.aggregate([ 
    {$match : {country : 'Spain', city : 'Salamanca'}},
    {$group : {_id : '$name',  total_students_number : {$sum : {$sum : '$students.number'} } } },
    {$sort : {total_students_number : -1}}
])

>> 출력결과 <<
[
  { _id: 'USAL', total_students_number: 91568 },
  { _id: 'UPSA', total_students_number: 22284 }
]



※ >>> 1개 도큐먼트 students 의 number 합계 구하기 예제 2 <<< ※ 

Enterprise universitydb> db.universities.aggregate([
    {$match : {country : 'Spain', city : 'Salamanca', name : 'UPSA'}},
    {$group : {_id : null,  total_students_number : {$sum : {$sum : '$students.number'} } } }
])

>> 출력결과 <<
[ { _id: null, total_students_number: 22284 } ]




※ >>> $out 예제 <<< ※    
==> $out 은 파이프라인의 결과(출력)를 컬렉션에 쓴다.
==> $out 연산자를 사용하면 파이프라인의 출력결과물을 자동적으로 컬렉션에 저장할 수 있게 해준다. 
==> $out 연산자는 컬렉션이 존재하지 않으면 켈렉션을 자동적으로 생성한 후 저장해주고, 만약에 컬렉션이 존재할 경우 컬렉션에 존재하던 도큐먼트를 모두 삭제한 후 저장해준다.

Enterprise universitydb> show collections

>> 실행결과 <<
courses
scores
universities


Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : '$subject', maxscore : {$max : '$score'} } },
      {$sort : {maxscore : -1}},
      {$out : 'scores_max'}
  ])
==> 위의 예제는 파이프라인의 결과를 scores_max 라는 컬렉션에 저장시키겠다는 것이다. 

마치 아래의 SQL 구문과 같은 뜻이다. 
create table scores_max
as
select subject, max(score) AS maxscore 
from scores
group by subject
order by maxscore desc;


Enterprise universitydb> show collections

>> 실행결과 <<
courses
scores
scores_max   
universities


Enterprise universitydb> db.scores_max.find().pretty() 

>> 실행결과 <<
[ { _id: '수학', maxscore: 98 }, { _id: '국어', maxscore: 97 } ]



Enterprise universitydb> db.scores.aggregate([
      {$group : {_id : '$subject', minscore : {$min : '$score'} } },
      {$sort : {minscore : 1}},
      {$out : 'scores_max'}
  ])
==> 위의 예제는 파이프라인의 결과를 scores_max 라는 컬렉션에 저장시키겠다는 것인데, 이미 scores_max 라는 컬렉션이 존재하므로 기존 도큐먼트를 모두 삭제한 후 저장시켜준다. 


Enterprise universitydb> db.scores_max.find().pretty()
[ { _id: '수학', minscore: 63 }, { _id: '국어', minscore: 71 } ]





※ >>> $unwind 예제 <<< ※ 

==> $unwind 연산자는 필드의 값이 배열일 때 사용하는 것으로서, 배열 필드를 분해하여 각 배열 요소를 별도의 도큐먼트로 만들어 준다.
    이를 통해 배열 필드를 사용한 그룹화나 집계 연산을 수행할 수 있게 된다.

 예를 들어, 아래와 같은 도큐먼트가 있다고 보자.
 {
   _id : ObjectId("661b9e1ee93865b1f48af61c"),
   prod_name : "커버낫 쿨 코튼",
   size : ["S", "M", "L"]
 }

 이 도큐먼트에서 size 필드의 값은 배열로 되어져 있는 것이다. 이 배열을 $unwind 연산자를 사용하여 분해하면 아래와 같은 결과를 얻게 된다.
 { _id : ObjectId("661b9e1ee93865b1f48af61c"),
   prod_name : "커버낫 쿨 코튼",
   size : "S"}
 {_id : ObjectId("661b9e1ee93865b1f48af61c"),
   prod_name : "커버낫 쿨 코튼",
   size : "M"}
 {_id : ObjectId("661b9e1ee93865b1f48af61c"),
   prod_name : "커버낫 쿨 코튼",
   size : "L"}



Enterprise universitydb> db.universities.aggregate([])
[
  {
    _id: ObjectId("668bae621e45930dc3c4d28a"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: [
      { year: 2014, number: 24774 },
      { year: 2015, number: 23166 },
      { year: 2016, number: 21913 },
      { year: 2017, number: 21715 }
    ]
  },
  {
    _id: ObjectId("668bae621e45930dc3c4d28b"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'UPSA',
    location: { type: 'Point', coordinates: [ -5.6691191, 17, 40.9631732 ] },
    students: [
      { year: 2014, number: 4788 },
      { year: 2015, number: 4821 },
      { year: 2016, number: 6550 },
      { year: 2017, number: 6125 }
    ]
  }
]



Enterprise universitydb> db.universities.aggregate([
	{ $match : { name : 'USAL' } },
	{ $unwind : '$students' }
  ]).pretty()

>> 실행결과 <<
[
  {
    _id: ObjectId("661b9e1ee93865b1f48af61c"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: { year: 2014, number: 24774 }
  },
  {
    _id: ObjectId("661b9e1ee93865b1f48af61c"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: { year: 2015, number: 23166 }
  },
  {
    _id: ObjectId("661b9e1ee93865b1f48af61c"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: { year: 2016, number: 21913 }
  },
  {
    _id: ObjectId("661b9e1ee93865b1f48af61c"),
    country: 'Spain',
    city: 'Salamanca',
    name: 'USAL',
    location: { type: 'Point', coordinates: [ -5.6722512, 17, 40.9607792 ] },
    students: { year: 2017, number: 21715 }
  }
]



Enterprise universitydb> db.universities.aggregate([
	{ $project : {_id : 0, name : 1, students : 1} }
  ]).pretty()

>> 실행결과 <<
[
  {
    name: 'USAL',
    students: [
      { year: 2014, number: 24774 },
      { year: 2015, number: 23166 },
      { year: 2016, number: 21913 },
      { year: 2017, number: 21715 }
    ]
  },
  {
    name: 'UPSA',
    students: [
      { year: 2014, number: 4788 },
      { year: 2015, number: 4821 },
      { year: 2016, number: 6550 },
      { year: 2017, number: 6125 }
    ]
  }
]


Enterprise universitydb> db.universities.aggregate([
	{ $project : {_id : 0, name : 1, students : 1} },
	{ $unwind : '$students' }
  ]).pretty()

>> 실행결과 <<
[
  { name: 'USAL', students: { year: 2014, number: 24774 } },
  { name: 'USAL', students: { year: 2015, number: 23166 } },
  { name: 'USAL', students: { year: 2016, number: 21913 } },
  { name: 'USAL', students: { year: 2017, number: 21715 } },
  { name: 'UPSA', students: { year: 2014, number: 4788 } },
  { name: 'UPSA', students: { year: 2015, number: 4821 } },
  { name: 'UPSA', students: { year: 2016, number: 6550 } },
  { name: 'UPSA', students: { year: 2017, number: 6125 } }
]



※ >>> $unwind 및 $group 예제 <<< ※ 

Enterprise universitydb> db.universities.aggregate([
	{ $project : {_id : 0, name : 1, students : 1} },
	{ $unwind : '$students' },
	{ $group : {_id : '$name', total_number : {$sum : '$students.number'} } }
  ]).pretty()

>> 실행결과 <<
[
  { _id: 'USAL', total_number: 91568 },
  { _id: 'UPSA', total_number: 22284 }
]




Enterprise universitydb> db.universities.aggregate([
	{ $match : {country : 'Spain', city : 'Salamanca', name : 'USAL'} },
	{ $project : {_id : 0, name : 1, students : 1} }
  ]).pretty()

>> 실행결과 <<
[
  {
    name: 'USAL',
    students: [
      { year: 2014, number: 24774 },
      { year: 2015, number: 23166 },
      { year: 2016, number: 21913 },
      { year: 2017, number: 21715 }
    ]
  }
]


Enterprise universitydb> db.universities.aggregate([
	{ $match : {country : 'Spain', city : 'Salamanca', name : 'USAL'} },
	{ $project : {_id : 0, name : 1, students : 1} },
	{ $unwind : '$students' }
  ]).pretty()

>> 실행결과 <<
[
  { name: 'USAL', students: { year: 2014, number: 24774 } },
  { name: 'USAL', students: { year: 2015, number: 23166 } },
  { name: 'USAL', students: { year: 2016, number: 21913 } },
  { name: 'USAL', students: { year: 2017, number: 21715 } }
]



Enterprise universitydb> db.universities.aggregate([
	{ $match : {country : 'Spain', city : 'Salamanca', name : 'USAL'} },
	{ $project : {_id : 0, name : 1, students : 1} },
	{ $unwind : '$students' },
	{ $group : {_id : '$name', total_number : {$sum : '$students.number'} } }
  ]).pretty()

>> 실행결과 <<
[ { _id: 'USAL', total_number: 91568 } ]




※ >>> $unwind 및 $group 2차 그룹짓기 예제 <<< ※ 

Enterprise universitydb> db.universities.aggregate([
	{ $project : {_id : 0, name : 1, students : 1} },
	{ $unwind : '$students' }
  ]).pretty()

>> 실행결과 <<
[
  { name: 'USAL', students: { year: 2014, number: 24774 } },
  { name: 'USAL', students: { year: 2015, number: 23166 } },
  { name: 'USAL', students: { year: 2016, number: 21913 } },
  { name: 'USAL', students: { year: 2017, number: 21715 } },
  { name: 'UPSA', students: { year: 2014, number: 4788 } },
  { name: 'UPSA', students: { year: 2015, number: 4821 } },
  { name: 'UPSA', students: { year: 2016, number: 6550 } },
  { name: 'UPSA', students: { year: 2017, number: 6125 } }
]



Enterprise universitydb> db.universities.aggregate([
	{ $project : {_id : 0, name : 1, students : 1} },
	{ $unwind : '$students' },
	{ $group : {_id : {name : '$name', 
	                   year : '$students.year'}, 
	            total_number : {$sum : '$students.number'} } }
  ]).pretty()

>> 실행결과 <<
[
  { _id: { name: 'USAL', year: 2014 }, total_number: 24774 },
  { _id: { name: 'USAL', year: 2016 }, total_number: 21913 },
  { _id: { name: 'UPSA', year: 2016 }, total_number: 6550 },
  { _id: { name: 'UPSA', year: 2014 }, total_number: 4788 },
  { _id: { name: 'USAL', year: 2017 }, total_number: 21715 },
  { _id: { name: 'UPSA', year: 2015 }, total_number: 4821 },
  { _id: { name: 'UPSA', year: 2017 }, total_number: 6125 },
  { _id: { name: 'USAL', year: 2015 }, total_number: 23166 }
]



Enterprise universitydb> db.universities.aggregate([
	{ $project : {_id : 0, name : 1, students : 1} },
	{ $unwind : '$students' },
	{ $group : {_id : {name : '$name', 
	                   year : '$students.year'}, 
	            total_number : {$sum : '$students.number'} } },
        { $sort : {_id : 1} }
  ]).pretty()

>> 실행결과 <<
[
  { _id: { name: 'UPSA', year: 2014 }, total_number: 4788 },
  { _id: { name: 'UPSA', year: 2015 }, total_number: 4821 },
  { _id: { name: 'UPSA', year: 2016 }, total_number: 6550 },
  { _id: { name: 'UPSA', year: 2017 }, total_number: 6125 },
  { _id: { name: 'USAL', year: 2014 }, total_number: 24774 },
  { _id: { name: 'USAL', year: 2015 }, total_number: 23166 },
  { _id: { name: 'USAL', year: 2016 }, total_number: 21913 },
  { _id: { name: 'USAL', year: 2017 }, total_number: 21715 }
]

'Full-Stack' 카테고리의 다른 글

Ajax  (0) 2024.08.01
JS VS Jquery  (0) 2024.08.01
VSCODE  (0) 2022.07.30