-
Mongodb - database and collectionmongoDB 2022. 3. 27. 17:21
이전 글(https://zzihyeon.tistory.com/45)에 이어서 mongoDB에 대해 알아보자
MongoDB는 data를 BSON documents로 저장하고 collection은 이 documents의 집합이다. 또한 database는 이 collection들의 집합이다. 즉 database > collection > document > data 라고 볼 수 있다.
이제 mongodb를 어떻게 사용하는지 알아보자.
Database
MongoDB에서 database는 여러개의 documents collections을 갖는다. 사용자는 어떤 database를 사용할지 선택할 수 있다.
- Mongodb를 설치 후 실행한다.
- mongo --port 27017 또는 mongo ${target_ip}:${target_port} 으로 mongosh로 들어간다. (Port를 변경하지 않았을 경우 27017이다.)
- mongosh에 들어왔으면 use testDB 명령어를 cmd창에 쓴다.
- Siwtched to db testDB 라는 글이 보이면 testDB라는 database로 접근한 것이다.
Create Database
만약 위에서 testDB라는 database가 기존에 존재하지 않았다면, mongoDB는 첫번 째 data를 insert할 때 이를 생성한다. Collection 역시 마찬가지다.
db.users.insertOne({ name: "zzihyeon" })
이제 testDB라는 database와 users라는 이름의 collection이 생성되었다.
Create a Collection
만약 collection이 존재하지 않았다면 첫 data를 insert하거나 index를 생성할 때 생성된다.
db.users.insertOne({ name:"zzihyeon" }) db.users.createIndex({ name: 1 });
Naming Restrictions
- Database
- 대소문자를 구분하지 않는다.
- Window (/\. "$*<>:|?), Unix,Linux(/\. "$) 는 사용되어서는 안된다.
- 길이 제한은 64characters이다.
- Collection
- 소문자로 시작되어야 한다.
- $, ""(empty string), null character, "system." prefix 을 포함해서는 안된다.
- 길이 제한은 255bytes이다.
- Data
- Field name은 null character를 포함해서는 안된다.
- ., $를 포함해서는 안된다. (5.0부터는 되지만 제한사항이 있다.)
- _id
- _id는 primary key로 사용되므로 collection에 반드시 unique해야만한다. 만약 _id가 sub field를 갖는다면 $로 시작해서는 안된다.
View
view는 동일한 database내에 있는 다른 collection이나 view에 대한 aggregation pipeline으로 정의되는 queryable object이다. 이는 disk에 저장하지 않고 client가 query요청을 할 때 계산되며 write operation은 불가능하다.
즉, 사용자 요청사항이 추상화되어 사용자는 실제 동작 여부에 대해 알지 못하고 간단한 쿼리로 다른 collection이나 view에 대한 aggregation pipeline 결과 값을 가져올 수 있다.
간단한 예를 들어보자
- User collection에 대해 아이디와 비밀번호를 제외한 view를 생성할 수 있고 이 view에 쿼리를 요청하면 이를 제외한 user정보를 줄 것이다.
- 만약 sensor data와 같이 raw 한 데이터를 갖고 있는 collection에 특정 기준으로 모아서 계산하는 view를 생성하면 application은 view에 find operation을 통해서 계산된 결과값을 쉽게 가져올 수 있다.
- 만약 2개의 collection의 정보를 모아서 줘야하는 view를 생성한다면 application은 이를 쉽게 가져올 수 있다.
Create View
Create View에는 두가지 방법이 있다.
db.createCollection( "$viewName", { "viewOn": "$source_collection", "pipeline: [$aggregation_pipeline], "collation":{} } )
db.createView( "$view_name", "$source_collection", [$aggregation_pipeline], { "collation":{$collation} } )
- view_name: view collection 이름
- source_collection: 이 view가 동작하는 베이스 collection
- aggregation_pipeline: mongo aggregation pipeline
- collation: sort order를 결정한다. 만약 { caseFirst: "upper"}라고 하면 대문자가 우선이다. (참고: https://www.mongodb.com/docs/manual/reference/collation/)
View Operation
- View는 read operation시에 on demand로 계산되고 mongoDB는 aggregation pipeline의 부분으로 read operation을 수행한다.
- View는 db.collection.mapReduce(), $text (aggregation의 첫번째 stage에서만 가능), $geoNear이 불가능하다.
- View에서 query를 사용할 때, Query(filter, projection, sort, skip, limit, db.collection.find())는 동일한 aggregation pieline stages로 변환되고 이 변환된 aggregation pipeline stages는 view가 설정한 aggregation pipeline의 맨 마지막에 붙여지며 기존 값을 변경하지는 않는다.
- Aggregation pipeline optimizer는 성능 향상을 위해 view 의 aggregation pipeline stage를 변형할 수 있으나 결과에 영항을 주지는 않는다.
Drop a view
- db.collection.drop() method를 사용한다.
Modify a View
- drop후 재생성하거나 collMod command를 사용한다.
Index Use and Sort Operations
- Source로 지정한 collection의 index를 사용한다.
- 4.4 version부터 find에 $natural sort를 지정할 수 있는데, 이는 default 이고 disk의 document order이다.(이전 버전은 지원하지 않음)
- 4.4 version부터 Pipeline subject가 100MB를 넘으면 allowDiskUse: true 옵션을 사용할 수 있다. Memory 대신 temp file으로 동작한다.
Projection Restrictions
find()에서 $, $elemMatch, $slice, $meta를 지원하지 않는다.
Supported operations
- db.collection.find()
- db.collection.findOne()
- db.collection.aggregate()
- db.collection.countDocuments()
- db.collection.estimatedDocumentCount()
- db.collection.count()
- db.collection.distinct()
'mongoDB' 카테고리의 다른 글
MongoDB - Read Concern (0) 2022.04.04 MongoDB CRUD - 어떻게 완화된 ACID (BASE) 인가? (0) 2022.03.28 MongoDB Time Series Collection - 3 (0) 2022.03.25 MongoDB Time Series Collection - 2 (0) 2022.03.25 MongoDB Time Series Collection - 1 (0) 2022.03.25