본문 바로가기
프로그래밍 개발/DB

MongoDB - Document Query(조회)

by Jinseok Kim 2021. 1. 18.
반응형

 

 

 Document Query(조회)

 

 

 

find() 메소드

 

articles라는 데이터 베이스 추가

db.articles.insert([
    {
        "title" : "article01",
        "content" : "content01",
        "writer" : "Velopert",
        "likes" : 0,
        "comments" : [ ]
    },
    {
        "title" : "article02",
        "content" : "content02",
        "writer" : "Alpha",
        "likes" : 23,
        "comments" : [
                {
                        "name" : "Bravo",
                        "message" : "Hey Man!"
                }
        ]
    },
    {
        "title" : "article03",
        "content" : "content03",
        "writer" : "Bravo",
        "likes" : 40,
        "comments" : [
                {
                        "name" : "Charlie",
                        "message" : "Hey Man!"
                },
                {
                        "name" : "Delta",
                        "message" : "Hey Man!"
                }
        ]
    }
])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

 

 

 

db.COLLECTION_NAME.find(query, projection)

 

query document Optional(선택적).  다큐먼트를 조회할 때 기준을 정합니다. 기준이 없이 컬렉션에 있는 모든 다큐먼트를 조회 할때는 이 매개변수를 비우거나 비어있는 다큐먼트 { } 를 전달하세요.
projection document Optional. 다큐먼트를 조회할 때 보여질 field를 정합니다.

 

 

 

 

> db.articles.find()

모든 다큐먼트 조회하기.

> db.articles.find()
{ "_id" : ObjectId("56c0ab6c639be5292edab0c4"), "title" : "article01", "content" : "content01", "writer" : "Velopert", "li
{ "_id" : ObjectId("56c0ab6c639be5292edab0c5"), "title" : "article02", "content" : "content02", "writer" : "Alpha", "likes
{ "_id" : ObjectId("56c0ab6c639be5292edab0c6"), "title" : "article03", "content" : "content03", "writer" : "Bravo", "likes ] }

 

 

 

 

 

 

> db.articles.find().pretty()

다큐먼트를 깔끔하게 조회하기.

> db.articles.find().pretty()
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c4"),
        "title" : "article01",
        "content" : "content01",
        "writer" : "Velopert",
        "likes" : 0,
        "comments" : [ ]
}
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c5"),
        "title" : "article02",
        "content" : "content02",
        "writer" : "Alpha",
        "likes" : 23,
        "comments" : [
                {
                        "name" : "Bravo",
                        "message" : "Hey Man!"
                }
        ]
}
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c6"),
        "title" : "article03",
        "content" : "content03",
        "writer" : "Bravo",
        "likes" : 40,
        "comments" : [
                {
                        "name" : "Charlie",
                        "message" : "Hey Man!"
                },
                {
                        "name" : "Delta",
                        "message" : "Hey Man!"
                }
        ]
}

 

 

 

 

 

 

 

> db.articles.find( { “writer”: “Alpha” } ).pretty()

writer 값이  “Alpha” 인 Document 조회

> db.articles.find({"writer": "Alpha"}).pretty()
{
        "_id" : ObjectId("600537dde2a7875ef704a81a"),
        "title" : "article02",
        "content" : "content02",
        "writer" : "Alpha",
        "likes" : 23,
        "comments" : [
                {
                        "name" : "Bravo",
                        "message" : "Hey Man!"
                }
        ]
}

 

 

 

 

 

 

> db.articles.find( { “likes”: { $lte: 30 } } ).pretty()

 likes 값이 30 이하인 Document 조회

> db.articles.find({"likes": {$lte: 30}}).pretty()
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c4"),
        "title" : "article01",
        "content" : "content01",
        "writer" : "Velopert",
        "likes" : 0,
        "comments" : [ ]
}
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c5"),
        "title" : "article02",
        "content" : "content02",
        "writer" : "Alpha",
        "likes" : 23,
        "comments" : [
                {
                        "name" : "Bravo",
                        "message" : "Hey Man!"
                }
        ]
}

 

비교(Comparison) 연산자

$eq (equals) 주어진 값과 일치하는 값
$gt (greater than) 주어진 값보다 큰 값
$gte (greather than or equals) 주어진 값보다 크거나 같은 값
$lt (less than) 주어진 값보다 작은 값
$lte (less than or equals) 주어진 값보다 작거나 같은 값
$ne (not equal) 주어진 값과 일치하지 않는 값
$in 주어진 배열 안에 속하는 값
$nin 주어빈 배열 안에 속하지 않는 값

> db.articles.find( { “likes”: { $gt: 10, $lt: 30 } } ).pretty() 

likes 값이 10보다 크고 30보다 작은 Document 조회

> db.articles.find( { "likes": { $gt: 10, $lt: 30 } } ).pretty()
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c5"),
        "title" : "article02",
        "content" : "content02",
        "writer" : "Alpha",
        "likes" : 23,
        "comments" : [
                {
                        "name" : "Bravo",
                        "message" : "Hey Man!"
                }
        ]
}

 

 

 

> db.articles.find( { “writer”: { $in: [ “Alpha”, “Bravo” ] } } ).pretty() 

 writer 값이 배열 [“Alpha”, “Bravo”] 안에 속하는 값인 Document 조회

 

 

 

 

논리 연산자

$or 주어진 조건중 하나라도 true 일 때 true
$and 주어진 모든 조건이 true 일 때 true
$not 주어진 조건이 false 일 때 true
$nor 주어진 모든 조건이 false 일때 true

 

> db.articles.find({ $or: [ { “title”: “article01” }, { “writer”: “Alpha” } ] })

title 값이 “article01” 이거나, writer 값이 “Alpha” 인 Document 조회

> db.articles.find({ $or: [ { "title": "article01" }, { "writer": "Alpha" } ] })
{ "_id" : ObjectId("600537dde2a7875ef704a819"), "title" : "article01", "content" : "content01", "writer" : "Velopert", "likes" : 0, "comments" : [ ] }
{ "_id" : ObjectId("600537dde2a7875ef704a81a"), "title" : "article02", "content" : "content02", "writer" : "Alpha", "likes" : 23, "comments" : [ { "name" : "Bravo", "message" : "Hey Man!" } ] }

 

 

 

> db.articles.find( { $and: [ { “writer”: “Velopert” }, { “likes”: { $lt: 10 } } ] } )

 writer 값이 “Velopert” 이고 likes 값이 10 미만인 Document 조회

> db.articles.find( { $and: [ { "writer": "Velopert" }, { "likes": { $lt: 10 } } ] } )
{ "_id" : ObjectId("56c0ab6c639be5292edab0c4"), "title" : "article01", "content" : "content01", "writer" : "Velopert", "likes" : 0, "comments" : [ ] }

> db.articles.find( { "writer": "Velopert", "likes": { $lt: 10 } } )
{ "_id" : ObjectId("56c0ab6c639be5292edab0c4"), "title" : "article01", "content" : "content01", "writer" : "Velopert", "likes" : 0, "comments" : [ ] }

 

 

 

 

 

$regex 연산자

$regex 연산자를 통하여 Document를 정규식을 통해 찾을 수 있다.

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
{ <field>: /pattern/<options> }

$options 리스트

i 대소문자 무시
m 정규식에서 anchor(^) 를 사용 할 때 값에 \n 이 있다면 무력화
x 정규식 안에있는 whitespace를 모두 무시
s dot (.) 사용 할 떄 \n 을 포함해서 매치

 

 

> db.articles.find( { “title” : /article0[1-2]/ } )

정규식 article0[1-2] 에 일치하는 값이 title 에 있는 Document 조회

> db.articles.find( { "title" : /article0[1-2]/ } )
{ "_id" : ObjectId("56c0ab6c639be5292edab0c4"), "title" : "article01", "content" : "content01", "writer" : "Velopert", "likes" : 0, "comments" : [ ] }
{ "_id" : ObjectId("56c0ab6c639be5292edab0c5"), "title" : "article02", "content" : "content02", "writer" : "Alpha", "likes" : 23, "comments" : [ { "name" : "Bravo", "message" : "Hey Man!" } ] }

 

 

db.articles.find({"writer":/Alpha/i})

writer가 Alphad이고 option이 i이므로 대소문자를 무시하고 조회한다.

> db.articles.find({"writer":/Alpha/i})
{ "_id" : ObjectId("60053de4e2a7875ef704a81d"), "title" : "article02", "content" : "content02", "writer" : "Alpha", "likes" : 23, "comments" : [ { "name" : "Bravo", "message" : "Hey Man!" } ] }

 

 

 

 

$where 연산자

$where 연산자를 통하여 javascript expression 을 사용 할 수 있다.

 

 

> db.articles.find( { $where: “this.comments.length == 0” } )

 comments field 가 비어있는 Document 조회

> db.articles.find( { $where: "this.comments.length == 0" } )
{ "_id" : ObjectId("56c0ab6c639be5292edab0c4"), "title" : "article01", "content" : "content01", "writer" : "Velopert", "likes" : 0, "comments" : [ ]

 

 

 

$elemMatch 연산자

$elemMatch 연산자는 Embedded Documents 배열을 쿼리할때 사용되고 mock-up data 에서는 comments 가 Embedded Document에 속한다.

 

 

db.articles.find( { “comments”: { $elemMatch: { “name”: “Charlie” } } } )

 comments 중 “Charlie” 가 작성한 덧글이 있는 Document 조회

> db.articles.find( { "comments": { $elemMatch: { "name": "Charlie" } } } )
{ "_id" : ObjectId("56c0ab6c639be5292edab0c6"), "title" : "article03", "content" : "content03", "writer" : "Bravo", "likes" : 40, "comments" : [ { "name" : "Charlie", "message" : "Hey Man!" }, { "name" : "Delta", "message" : "Hey Man!" } ] }

 

 

 

 

{
    "username": "velopert",
    "name": { "first": "M.J.", "last": "K."},
    "language": ["korean", "english", "chinese"]
  }

 

Embedded Document 배열이 아니라 아래 Document의 “name” 처럼 한개의 Embedded Document 일 시에는,

> db.users.find({ "name.first": "M.J."})

다음과 같이 쿼리합니다.

 

 

 

> db.users.find({ "language": "korean"})

그리고 Document의 배열이아니라 그냥 배열일 시에는 다음과 같이 Query 합니다.

 

 

 

 

 

 

 

 

projection

find() 메소드의 두번째 parameter 인 projection

쿼리의 결과값에서 보여질 field를 정하는 것이다.

 

 

 

 

 

> db.articles.find( { } , { “_id”: false, “title”: true, “content”: true } )

article의 title과 content 만 조회

> db.articles.find( { } , { "_id": false, "title": true, "content": true } )
{ "title" : "article01", "content" : "content01" }
{ "title" : "article02", "content" : "content02" }
{ "title" : "article03", "content" : "content03" }

 

 

 

$slice 연산자

projector 연산자 중 $slice 연산자는 Embedded Document 배열을 읽을때 limit 설정

 

 

> db.articles.find( { “title”: “article03” }, { comments: { $slice: 1 } } )

title 값이 article03 인 Document 에서 덧글은 하나만 보이게 출력.

$slice 가 없었더라면, 2개를 읽어와야하지만 1개로 제한을 두었기에 한개만 출력하게된다.

> db.articles.find({"title": "article03"}, {comments: {$slice: 1}}).pretty()
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c6"),
        "title" : "article03",
        "content" : "content03",
        "writer" : "Bravo",
        "likes" : 40,
        "comments" : [
                {
                        "name" : "Charlie",
                        "message" : "Hey Man!"
                }
        ]
}

 

 

 

 

$elemMatch 연산자

query 연산자 중 $elemMatch와 사용법은 같다.

 

 

 comments 중 “Charlie” 가 작성한 덧글이 있는 Document 중 제목, 그리고 Charlie의 덧글만 조회

db.articles.find(
...     {
...         "comments": {
...             $elemMatch: { "name": "Charlie" }
...         }
...     },
...     {
...         "title": true,
...         "comments": {
...             $elemMatch: { "name": "Charlie" }
...         },
...         "comments.name": true,
...         "comments.message": true
...     }
... )
{ "_id" : ObjectId("56c0ab6c639be5292edab0c6"), "title" : "article03", "comments" : [ { "name" : "Charlie", "message" : "Hey Man!" } ] }
반응형

'프로그래밍 개발 > DB' 카테고리의 다른 글

MongoDB - Document 수정  (0) 2021.01.19
MongoDB - Document Query(조회) 2  (0) 2021.01.18
MongoDB - 생성 및 제거하기  (0) 2021.01.15
MongoDB - 기본 설치 및 개념  (0) 2021.01.14
Mysql - 테이블 분리하기와 JOIN  (0) 2021.01.09

댓글