MongoDB란?
비관계형 데이터베이스(NoSQL DB)의 하나
MySQL, Oracle 등의 관계형 데이터베이스는 신뢰도를 더 중요시하기 때문에 SQL문을 읽어들이고 실행하는 데 많은 리소스를 들인다. 반면, 비관계형 데이터베이스는 성능을 최우선으로 생각하기 때문에 실시간 처리나 대용량 트래픽을 다루는 메시징 시스템에 활용된다.
MongoDB(NoSQL)는 다음과 같이 관계형 데이터베이스와 대응된다.
관계형 데이터베이스 | MongoDB |
테이블(Table) | 컬렉션(Collection) |
레코드(Record) | 문서 객체(Document) |
즉, 데이터베이스는 컬렉션의 집합이며, 각각의 컬렉션은 여러 개의 문서 객체(Document)를 가진다.
이때, 문서 객체는 레코드와 달리 각 객체마다 똑같은 필드를 지니지 않아도 된다는 차이점이 있다.
실행하기
윈도우 기준 환경변수를 추가해줘야 한다(4.4 버전 기준).
C:\Program Files\MongoDB\Server\4.4\bin
Client로서 MongoDB 사용하기
$ mongo
Server로서 MongoDB 사용하기
Node.js에서 MongoDB를 사용하기 위해선 먼저 프롬프트에서 다음과 같은 명령어로 데이터베이스 서버를 실행시켜줘야 한다.
$ mongod --path <데이터가 저장될 경로> //mongod --path /Users/user/database/local
기본적인 MongoDB 명령어 (shell 상에서 실행)
현재 데이터베이스 확인
db
데이터베이스 변경
use local // local로 변경
Insert
하나의 document 삽입: db.collection.insertOne()
db.inventory.insertOne([
{ item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] }
]);
여러 document 삽입: db.collection.insertMany()
db.inventory.insertMany([
{ item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
{ item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "plain"] },
{ item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);
Select
컬렉션 내 모든 document 출력: db.collection.find()
db.inventory.find()
db.inventory.find().pretty() // formatting
컬렉션 내 특정 document 출력: db.collection.find({<field>:<value>})
db.inventory.find( { status: "D" } );
db.inventory.find( { qty: 0, status: "D" } );
db.inventory.find( { "size.uom": "in" } )
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
Update
컬랙션 내 하나의 document 업데이트: db.collection.updateOne(<filter>, <update>, <options>)
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
컬렉션 내 여러 document 업데이트: db.collection.updateMany(<filter>, <update>, <options>)
db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)
컬렉션 내 하나의 document replace: db.collection.replaceOne(<filter>, <update>, <options>)
update와 달리 필드 변경이 아니라 문서 객체 전체를 변경한다.
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
Delete
삭제 연산은 예제와 함께 좀 더 구체적으로 살펴보도록 하자.
다음은 orders 컬렉션의 구조이다.
// orders Collection structure
{
_id: ObjectId("563237a41a4d68582c2509da"),
stock: "Brent Crude Futures",
qty: 250,
type: "buy-limit",
limit: 48.90,
creationts: ISODate("2015-11-01T12:30:15Z"),
expiryts: ISODate("2015-11-01T12:35:15Z"),
client: "Crude Traders Inc."
}
컬렉션 내 하나의 document 삭제: db.collection.deleteOne()
try {
db.orders.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
} catch (e) {
print(e);
}
{ "acknowledged" : true, "deletedCount" : 1 }
컬랙션 내 여러 document 삭제: db.collection.deleteMany()
try {
db.orders.deleteMany( { "client" : "Crude Traders Inc." } );
} catch (e) {
print (e);
}
{ "acknowledged" : true, "deletedCount" : 10 }
try {
db.orders.deleteMany( { "stock" : "Brent Crude Futures", "limit" : { $gt : 48.88 } } );
} catch (e) {
print (e);
}
{ "acknowledged" : true, "deletedCount" : 8 }
MongoDB CRUD document
'웹 > Node.js' 카테고리의 다른 글
[Node.js] 모듈화에 사용되는 module.exports와 exports의 차이 (0) | 2021.04.13 |
---|---|
[Node.js] JWT: Access Token & Refresh Token 인증 구현 (16) | 2021.04.06 |
[Node.js] Express 6: 쿠키와 세션 (Cookie & Session) (2) | 2021.02.22 |
[Node.js] Express 5: 에러 처리(Error Handling) (0) | 2021.02.22 |
[Node.js] Express 4: 라우터(Router) (1) | 2021.02.20 |