Database/MongoDB

Mongo DB #4_ 데이터 자료형, find 함수, 쿼리 연산자

Tigercow.Door 2017. 11. 5. 16:38


안녕하세요.

오늘은 mongoDB에서 데이터 자료형과 find함수, 쿼리연산자에 대해서 알아보도록 하겠습니다.

내용에 대한 피드백이나 궁금한 점은 언제든지 댓글을 남겨주세요 :)


1. 데이터 자료형(Datatypes)


MongoDB에는 많은 데이터 자료형을 지원합니다. 그 중 몇가지에 대해서만 알아보도록 하겠습니다.


String

 String은 데이터를 저장할때 가장 많이 사용되는 데이터 자료형 중 하나입니다. MongoDB에서 String은 반드시 UTF-8 형식만 가능합니다.

Integer

 숫자값을 저장할때 주로 사용되는 자료형입니다. Integer는 서버에 따라서 32bit 또는 64bit입니다.

Boolean

 이것은 참(true) 또는 거짓(false)를 나타내는 값을 저장하는 자료형입니다.

Double

 Double 자료형은 부동 소수점 값을 저장하는데 사용됩니다.

Min/Max keys

 이것은 BSON요소의 최저 값과 최고값을 비교하는데 사용됩니다.

Arrays

 Arrays 자료형은 배열 또는 여러 값을 하나의 키에 저장하는데 사용됩니다.

Timestamp

 해당 자료형은 문서가 수정되거나 추가될때 기록하기 편리합니다.

Object

 해당 자료형은 embedded documents에 사용됩니다.

Null

 Null 자료형은 Null 값을 저장할 떄 사용됩니다.

Symbol

 해당 자료형은 문자열(String)과 동일하게 사용됩니다. 하지만 일반적으로 특정 기호 유형을 사용하는 언어로 사용되고 있습니다.

Date

 Date 자료형은 현재의 날짜 또는 시간을 UNIX시간 형식으로 저장하는 데 사용됩니다. Date 객체를 만들어 내며 일, 월, 년을 전달하여 자신의 날짜 및 시간을 지정할 수 있습니다.

Object ID

 이것은 document의 ID를 저장하는데 사용됩니다.

Binary data

 이것은 2진수 데이터를 저장하는데 사용됩니다.

Code

 이것은 document 내부에 JavaScript 코드를 저장하는데 사용됩니다.

Regular expression

 이것은 정규 표현식을 저장하는데 사용됩니다.



2. Document 검색:: find() 함수


이번에는 Document를 검색하는 find() 함수에 대해서 알아보도록 하겠습니다.

먼저 find method에 대한 정의는 아래와 같습니다.


db.COLLLECTION-NAME.find(query,projection)


Parameter

Type

Description

query

document

Optional(선택적임).

검색시 보다 구체적인 내용을 반환받기 위해 조건을 입력. default로는 모든 값을 검색.

projection

document

Optional(선택적임).

검색후 반환 값(출력 값)을 어떤식으로 할지 결정함. default로는 모든 값을 출력. 


find는 위와 같은 구조를 가진 함수입니다. 그럼 바로 사용해볼까요?



위의 사진에서 순서대로 확인해보겠습니다.

먼저 사용할 데이터베이스를 선택하고, 어떠한 collection들이있는지 확인해보았습니다.

그리고 존재하는 firstCollection을 find()함수로 확인해보았습니다.

하나의 document가 존재하여 2개의 document를 추가하였습니다.

이후 find() 함수를 한번더 사용하였습니다.


이때, document가 한줄로 출력되서 보기 힘드신가요?

이러한 시각적 불편함을 해결하기위해 pretty() 함수가 있습니다.

함수이름대로, 보기좋게 document를 출력해주는 함수입니다.

아래 사진을 보시면 잘 이해가 가실거에요.



pretty() 함수를 사용하지 않았을떄와 사용했을떄의 차이가 보이시나요?



2-1. find() 함수 활용하기


find() 함수를 좀 더 응용해보도록 할게요.

기본적으로, collection에 있는 모든 다큐먼트를 조회하려면 어떻게 해야 할까요?

네. 맞습니다. 위에서 했던 것처럼,

db.COLLECTION-NAME.find()

를 입력하면 해당 컬렉션의 모든 document가 조회됩니다.


이제 몇가지 조건을 추가해볼게요.

위의 firstCollection을 바탕으로 하여, 성별(sex)가 남자(male)인 다큐먼트만 조회하려면 어떻게 해야할까요?

find() 함수의 정의에서 살펴본 것처럼, query parameter에 조건을 추가하면 되겠죠?


db.firstCollection.find({"sex":"male"})



한번 더 해보겠습니다.

그럼, 전공이 운동(sport)인 다큐먼트의 이름(name)을 조회하려면 어떻게 해야할까요?

네, 바로 query와 projection 두개다 적절히 조건을 추가하면 되겠습니다.


db.firstCollection.find({"major":"sport"},{"_id":false,"name":true})




3. 쿼리 연산자(Query operators)


이번에는 MongoDB에서 사용되는 쿼리 연산자(Query operators)에 대해서 살펴보겠습니다.

쿼리연산자는 위에서 알아본 find() 함수와 함께 응용되어 다양한 기능을 할 수 있습니다.

쿼리 연산자는 프로그래밍 언어에서 사용되는 비교(Comparison), 논리(Logical)등과 같은 다양한 종류의 연산자가 있습니다.

하나씩 살펴보기에 앞서, 연산자들에 대한 예제를 진행하기 위해서 기본 muck up data를 설정하겠습니다.


insert 코드는 아래와 같으며 그에 대한 muck up data를 find()함수로 확인하였습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
db.operatorTest.insert([
{
    "name":"John""sex":"male""major":"ECE""score":76"grade":"B"
},{
    "name":"Kai""sex":"male""major":"art""score":99"grade":"A"
},{
    "name":"Jane""sex":"female""major":"ECE""score":90"grade":"A"
},{
    "name":"Ko""sex":"male""major":"ECE""score":21"grade":"F"
},{
    "name":"Ki""sex":"female""major":"dance""score":79"grade":"B"
},{
    "name":"Bro""sex":"female""major":"art""score":68"grade":"C"
},{
    "name":"Victor""sex":"male""major":"ECE""score":49"grade":"D"
},{
    "name":"Kan""sex":"female""major":"art""score":61"grade":"C"
}
])
cs





3-1. 비교(Comparison)


연산자

설명(Description)

$eq

Matches values that equal to a specified value.

주어진 값과 동일한 값

$gt

Matches values that are greater than a specified value.

주어진 값보다 더 큰 값

$gte

Matches values that are greater than or equal to a specified value.

주어진 값보다 크거나 같은 값

$lt

Matches values that are than a specified value.

주어진 값보다 더 작은 값

$lte

Matches values that are less than or equal to a specified value.

주어진 값보다 작거나 같은 값

$ne

Matches all values that are not equal to a specified value.

주어진 값과 동일하지 않은 값

$in

Matches any of the values specified in an array.

주어진 배열에 속하는 어떤 값

$nin

Matches none of the values specified in an array.

주어진 배열에 속하지 않는 어떤 값


예제)

A) score의 값이 70이하이고, 45초과를 하는 document를 조회하여라.




B) grade가 [A,B,C,D]에 속하지 않는 document를 조회하여라.




C) major가 art인 document를 조회하여라.




3-2. 논리(Logical)


연산자

설명(Description)

$or

Joins query clauses with a logical OR returns all documents that match the conditions of either clause.

논리적 OR과 같은 의미로써, 주어진 조건 중 하나라도 true일때 true를 반환합니다.

$and

Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.

논리적 AND와 같은 의미로써, 주어진 조건 중 모든 조건이 true일때 true를 반환합니다.

$not

Inverts the effect of a query expression and returns documents that do not match the query expression.

주어진 조건에 대해 반대 논리를 반환하는 것으로써, 주어진 조건이 false일때 true를 반환합니다.

$nor

Joins query clauses with a logical NOR returns all documents that fail to match both clauses.

주어진 조건 중 모든 조건이 false일때 true를 반환합니다.


예제)

A) 성별이 남자(male)이고 score가 50이하인 document를 조회하여라.




B) 전공(major)가 ECE가 아니고 score가 80미만이 아닌 document를 조회하여라.




C) 전공(major)가 ECE가 아니거나 score가 80미만이 아닌 document를 조회하여라.




3-3. 요소(Element)


연산자

설명(Description)

$exists

Matches documents that have the specified field.

주어진 필드를 가진 documents를 조회합니다.

$type

Selects documents if a field is of the specified type.

field가 지정된 유형인 경우 해당 documents를 선택합니다.



3-4. 평가(Evaluation)


연산자

설명(Description)

$mod

Performs a modulo operation on the value of a field and selects documents with a specified result.

field 값에 대한 modulo 연산을 수행하고 해당 결과가 있는 documents를 선택합니다.

$regex

Selects documents where values match a specified regular expression.

정규 표현식(regular expression)과 일치하는 documents를 선택합니다.

$text

Performs text search.

텍스트 검색을 수행합니다.

$where

Matches documents that satisfy a JavaScript expression.

JavaScript 표현식에 만족하는 documents를 조회합니다.



3-5. 배열(Array)


연산자

설명(Description)

$all

Matches arrays that contain all elements specified in the query.

query에 지정된 모든 요소를 포함하는 배열을 찾습니다.

$elemMatch

Selects documents if element in the array field matches all the specified $elemMatch conditions.

배열 field의 요소가 지정된 $elemMatch의 조건과 모두 일치하는 documents를 선택합니다.

$size

Selects documents if the array field is a specified size.

배열 field가 지정된 크기인 경우의 documents를 선택합니다.



네, 이렇게 해서 MongoDB에서 데이터 자료형과, find() 함수, 다양한 연산자에 대해서 알아보았습니다.

내용에 대한 피드백이나 궁금한 점은 언제나 댓글을 이용해주세요 :)

728x90