[MongoDB] CRUD

2020. 12. 15. 02:14Database/MongoDB

※ 메뉴얼(docs.mongodb.com/manual/reference/sql-comparison/)에 SQL에 따른 MongoDB 사용 방법이 적혀있다.

1. 참고

1) '_id' 필드

MongoDB에는 Collection에 저장되어있는 각 Document에는 고유의 식별자((RDBMS에서는 PK)가 필요하다. 만약 Document에 '_id' 필드가 선언되어 있지 않을 경우 MongoDB는 '_id' 필드를 ObjectID 값으로 추가해준다.

 

인덱스는 MongoDB에서 데이터 쿼리를 효율적으로 사용할 수 있게 해준다. 인덱스가 없을 경우 컬렉션의 데이터를 하나씩 조회하여 스캔하지만, 인덱스를 사용하면 더 적은 횟수의 조회로 원하는 데이터를 찾을 수 있다. 이는 MongoDB가 인덱스에 대해 B-Tree를 구성하고, B-Tree 이진탐색으로 조회하기 때문에 O(logN)의 시간복잡도를 가져, 빠르다. 인덱스는 Single Field Index(기본 '_id'), Compound Index, Multikey Index, Geospatial Index, Text Index, Hashed Index가 있다.

2) 원자성 (Atomicity)

원자성은 한 트랜잭션 내에서 실행한 작업들은 모두 하나의 작업으로 간주하여 모두 성공 하거나 모두 실패되어야한다. MongoDB에서는 Document단위로 이런 원자성을 보장한다.

3) Database

데이터베이스 생성은 use 명령으로 생성한다. 이미 있을 경우에는 해당 데이터베이스를 사용한다. 1개 이상의 Collection이 존재해야 데이터 베이스 리스트에서 확인할 수 있다. 삭제할 경우에는 use 명령으로 데이터베이스에 스위치한 상태에서 진행해야한다.

// 현재 사용중인 데이터베이스 확인
db

// 데이터베이스 목록 확인
show dbs

// 데이터베이스 상태 확인
db.stats()

// 데이터베이스 제거
db.dropDatabase()

4) Collection

Collection을 생성할 때의 옵션은 Document 타입으로 구성된 해당 컬렉션의 설정값이다.

db.createCollection( <컬렉션명>, <옵션> )
옵션 설명
capped Boolean 타입으로 true 설정 시 capped를 활성화한다. capped는 고정된 크기를 가진 컬렉션으로 size가 초과되면 가장 오래된 데이터를 덮어쓴다. 이 값을 true로 설정할 경우 반드시 size 값을 지정해주어야 한다.
autoIndex Boolean 타입으로 true 설정 시 '_id' 필드에 index를 자동 생성한다. 기본값은 false이다.
size Number 타입으로 capped를 위해 해당 컬렉션의 최대 size를 byte로 지정한다.
max Number 타입으로 해당 컬렉션에 추가할 수 있는 최대 Document 갯수를 설정한다.
// 컬렉션 목록 확인
show collections

// 컬렉션 제거
db.<컬렉션명>.drop()

// 컬렉션명 변경
db.<OLD컬렉션명>.renameCollection("<NEW컬렉션명>")

 

 

 

2. Create Opertations (Insert Document)

Create Operations

1) insertOne()

insertOne() 메서드가 성공하게 되면 Document의 '_id'를 반환해준다.

db.inventory.insertOne({ 
  item: "canvas", 
  qty: 100, 
  tags: ["cotton"], 
  size: { h: 28, w: 35.5, uom: "cm" } 
})

2) insertMany()

insertOne() 메서드와는 다르게 여러 개의 Document를 insert 하기위한 명령어이다.

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
   { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
   { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

3) insert()

Single Document 혹은 Multiple Document를 insert 하기 위한 명령어이다.

 

 

 

3. Read Operations (Find Document)

Read Opertations

1) 일반 조회

// 전체 조회
db.inventory.find( { } )

// 조건 조회
db.inventory.find( { item: "canvas" } )
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

// 필드와 내부 필드 붙인 조회
db.inventory.find( { "size.uom": "cm" } )

// Operator를 이용한 조회 (h는 14 이하, uom이 cm인 Document)
db.inventory.find( { "size.h": { $lt: 14 }, "size.uom": "cm" } )

2) 필요 데이터 조회

'_id' 필드를 포함한 모든 데이터가 아닌 일부 데이터만 조회하는 경우 사용하는 방법은 다음과 같다.

db.collection.find( { <조건> }, { <필요 필드> } )
// '_id'를 포함한 item 필드 조회
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } }, { item: 1 } )

// '_id'를 제외한 item 필드 조회
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } }, { _id: 0, item: 1 } )

// '_id'와 'item'을 제외한 모든 필드 조회
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } }, { _id: 0, item: 0 } )

3) 배열 조건 조회

특정 필드 값이 배열로 되어있고, 그 데이터를 필드를 이용해 조회하는 방법은 다음과 같다.

db.collection.find( { <필드명>: { &all: [ <값1>, <값2> ] } } )

4) 조건 조회에 사용되는 비교 연산자

연산자 설명
$eq 정의된 값과 동일한 값을 매칭 (equal)
$gt 정의된 값보다 큰 값을 매칭 (greater than)
$gte 정의된 값보다 크거나 같은 값을 매칭 (greater then & equal)
$in 배열에 정의된 값 내에 있는 값을 매칭 (in)
$lt 정의된 값보다 작은 값을 매칭 (less than)
$lte 정의된 값보다 작거나 같은 값을 매칭 (less than & equal)
$ne 정의된 값과 다른 모든 값을 매칭
$nin 배열에 정의된 값에 없는 값을 매칭

5) 조건 조회에 사용되는 논리 연산자

연산자 설명
$and 논리 AND를 이용한 조인 쿼리절을 통해 조건에 일치하는 모든 Document 반환
$not 쿼리문의 효과를 반전하고 조건에 일치하지 않은 Document 반환
$nor 논리 NOR를 이용한 조인 쿼리절을 통해 조건에 일치하지 않는 모든 Document 반환
$or 논리 OR를 이용한 조인 쿼리절을 통해 조건에 일치하는 모든 Document 반환

6) Null 값과 필드 존재 여부 조회

조건에 null 값을 입력하면, 필드가 null인 값도 조회하지만, 필드가 존재하지 않는 Document도 조회한다.

db.inventory.insertMany([ 
  { _id: 1, item: null }, 
  { _id: 2 }
])

db.inventory.find( { item: null } )

필드가 존재하지 않는 Document를 조회하기 위한 방법과 필드의 값이 null인 값을 조회하는 방법은 다음과 같다.

// 존재하지 않는 필드 조회
db.inventory.find( { item: { $exists: false } } )

// 필드값이 null인 필드 조회
db.inventory.find( { item: { $type: 10 } } )

※ 10번은 null type이다. (docs.mongodb.com/manual/reference/bson-types/)

7) Cursor

MongoDB에서는 find() 함수를 사용하면 객체 타입은 Cursor 형태의 객체로 반환이 된다. 기본적으로 Cursor 반복을 최대 20회로 조회한다. Curso에 저장하여 하나씩 반복하여 출력하는데 커서를 변수로 지정하여 사용하지 않을 경우 최대 20개의 Document만 조회된다.

db.inventory.insertMany([ 
  { _id: 1 }, { _id: 2 }, 
  { _id: 3 }, { _id: 4 },
  { _id: 5 }, { _id: 6 },
  { _id: 7 }, { _id: 8 },
  { _id: 9 }, { _id: 10 },
  { _id: 11 }, { _id: 12 },
  { _id: 13 }, { _id: 14 },
  { _id: 15 }, { _id: 16 },
  { _id: 17 }, { _id: 18 },
  { _id: 19 }, { _id: 20 },
  { _id: 21 }, { _id: 22 }
])

// 20까지만 출력
var myCursor = db.inventory.find( { } );
myCursor

// 22 모두 출력
var myCursor = db.inventory.find( { } );
while(myCursor.hasNext()) {
  print(tojson(myCursor.next()));
}

// 22 모두 출력
var myCursor = db.inventory.find( { } );
myCursor.forEach(printjson);

// 배열 형태 변환
var myCursor = db.inventory.find( { } );
var documentArray = myCursor.toArray();
var myDocument = documentArray[3];

Java에서 Cursor를 사용하는 방법은 다음과 같다.

MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
FindIterable<Document> findIterable = collection.find(query.getQuery());
MongoCursor<Document> cursor = findIterable.iterator();

try {

  if(cursor.hasNext()) return cursor.next();

} finally {
  cursor.close();
}

※ 그 외에는 정렬 기능, 출력 갯수 제한, 출력 시작 설정 등이 있다.

 

 

 

4. Update Operations (Update, Replace Document)

Update Operations

1) updateOne()

하나의 Document를 수정한다. Update 할 때에는 조건을 넣어 수정할 Document를 지정하는데 여러 Document가 조회될 경우 가장 처음 Document를 수정한다.

db.inventory.updateOne(
  { item: "paper" }, 
  {
    $set: { "size.uom": "cm", status: "P" },
    $currentDate: { lastModified: true }
  }
)

2) updateMany()

여러 데이터를 한번에 수정하기 위해 사용되는 메서드이다.

db.inventory.updateMany(
  { "qty": { $lt: 50 } }, 
  {
    $set: { "size.uom": "in", status: "P" },
    $currentDate: { lastModified: true }
  }
)

3) replaceOne()

updateOne()과 updateMany() 메서드는 $set을 통해 필드를 수정했지만, replaceOne()은 다르게 들어온 인자값으로 Document를 대체한다.

db.inventory.replaceOne(
  { item: "paper" }, 
  { item: "paper",
    instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ]
  }
)

 

 

 

5. Delete Operations (Delete Document)

Delete Operations

1) deleteOne()

조회된 Document 중에서 가장 첫번째 Document를 삭제한다.

2) deleteMany()

deleteMany() 메서드는 특정 Document 뿐만 아닌 전체 Document를 삭제할 수 있다.

db.inventory.deleteMany( { } )
db.inventory.deleteMany( { <필드> : <값> } )

[참고] docs.mongodb.com/manual/crud/

[참고] junghwanta.tistory.com/30

[참고] sjh836.tistory.com/100

728x90

'Database > MongoDB' 카테고리의 다른 글

[MongoDB] Text Search  (0) 2020.12.17
[MongoDB] Bulk Write, Retryable Write/Read  (0) 2020.12.16
[MongoDB] MongoDB 설치  (0) 2020.12.12
[MongoDB] SQL, NoSQL, MongoDB  (0) 2020.12.12