본문 바로가기
Database/MongoDB

CRUD Operations

by mansoorrr 2023. 9. 25.

CRUD Operations는 documents의 Create, Read, Update, Delete를 의미한다.

 

1. Create Operations

Create Operation에는 create와 insert가 있다. 만약 현재 collection이 없다면 insert는 새로운 collection을 만든다.

collection에 documents를 만드x는 방법은  대표적으로 두가지가 있다.

#----- 단일 document 입력시
<사용할db>.<사용할collection>.insertOne(<document>)
ex) inventory collection에 document추가시
db.inventory.insertOne(
	{ item: "canvas", qty: 100, tags: ["cotton"], size: {h:28, w:35.5, uom: "cm"} }
    )

#----- 다중 documents 입력시
<사용할db>.<사용할 collection>.insertMany([<document>, <document>, <document>])
ex) inventory collection에 document들 추가시
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" } }
	])

 

2. Read Operations

Read Operations는 하나의 collection에서 document를 검색한다. 기본적으로 documents들을 찾기 위해 다음과 같은 메서드를 제공한다.

#----- 제공하는 method
<해당db>.<해당 collection>.find(<query>, <projection>).<cursor> 

ex) 사용예시
1. 조건: user라는 collection에서 age가 18초과인 데이터들 중 5개만 보고싶다. 단, 필드는 name과 address만 본다.
2. 조건에 대한 설명
  가) <collection>: user
  나) <query>: age가 18 초과인 데이터 중에
  다) <projection>: 필드는 name과 add만 
  라) <cursor>: 데이터들 중 5개만 보고싶다
3. 조건 => 쿼리
  db.user.find(
	{ age: { $gt: 18 } },
    { name: 1, address: 1 } # 1: true
    ).limit(5)

 

가. 추가 문법

1) 조건지정 쿼리(in, and, or, and/or)

특정 필드에 조건을 걸어 데이터를 조회하고 싶을때 조건지정 쿼리를 사용한다. 대표적으로 in, and, or이 있다.

#----- in: 인자로 받는 array중 하나라도 있는 document출력
1. 조건: status에 A나 D가 들어있는 document에서 "_id", "status", "qty" 필드만 출력
2. 쿼리
    db.inventory.find( 
        {
            status: {
                $in: ["A", "D"]
            }
        },
        {
            "_id": 1,
            "status":1,
            "qty": 1
        }
        )


#----- and: 인자로 받는 조건 모두 만족하는 document 출력
1. 조건: status가 "A"이면서 qty가 30미만인 document에서 "_id", "qty", "status"만 출력
2. 쿼리
	db.inventory.find(
    {
        status: "D",
        qty: {
            $lte: 75
        }
    },
    { _id: 1, qty: 1, status: 1}
    )


#----- or: 인자로 받는 조건에 하나라도 부합하는 document 출력
1. 조건: status가 "A"이거나 qty가 75미만인 document에서 "_id", "item", "qty", "status"만 출력
2. 쿼리
	db.inventory.find(
    {
        $or: [
            { status: "A" },
            { qty: { $lt: 30 } }
            ]
    },
    { _id: 1, item: 1, qty: 1, status: 1}
    )
    
    
#----- and, or 동시조건
1. 조건: status가 "P" 이면서 qty가 30미만이거나, item이 p로 시작하는 document에서 _id, status, qty, item 출력
2. 쿼리
    db.inventory.find(
        {
            status: "P",
            $or: [
                { qty: { $lt: 30 } },
                { item: { $regex: '^m' } }
                ]
        },
        { _id: 1, status: 1, qty: 1, item: 1 }
        )

2) 중첩 document  검색 및 일치

document안에 필드가 document로 이루어져 있는 데이터를 찾을 때는 찾고자하는 document안에 있는 필드들의 순서가 정확히 일치해야한다.

 

#----- 이런 데이터가 있을때
db.inventory.insertMany( [
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);


#----- size: { h: 14, w: 21, uom: "cm" } 에 해당하는 데이터는 찾을 수 있다.
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )


#----- size: { w: 21, h: 14, uom: "cm" } 에 해당하는 데이터는 찾을 수 없다.
db.inventory.find(  { size: { w: 21, h: 14, uom: "cm" } }  )


#----- size: { w: 21, h: 14, uom: "cm" } 에서 uom에 대한 부분에 조건을 걸고 싶다면 '.'을 사용한다
db.inventory.find( { "size.uom": "in" } ) # size.uom이 "in"인 document 찾기
db.inventory.find( { "size.h" : { $lt: 30 } } ) # size.h가 30보다 작은 document 찾기
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" }  ) # and조건

3) value가 array일때

# ----- 이런 데이터가 있을때
db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);


# ----- 정확히 특정 요소가 있는 경우를 찾고 싶을 때
db.inventory.find( 
    {
        tags: ["red", "blank"]
    }
    )


# ----- 특정 요소가 들어있는 값을 모두 찾고 싶을 때 
# 1) $all operator 사용
db.inventory.find(
    {
        tags: {
            $all: ["red", "blank"]
        }
    }
    )
    
# 2) ":"로 사용
db.inventory.find( { tags: "red" } )
db.inventory.find( { dim_cm: { $gte: 21 } } )

# 3) ":"로 사용하면서 조건(or)
db.inventory.find( 
    {
        dim_cm: {
            $gte: 15, $lte: 20
        }
    }
    )

# 4) "elemmatch"를 사용하여 조건(or)
db.inventory.find( 
    {
        dim_cm: {
            $elemMatch: { $gt: 22, $lt: 30 }
        }
    }
    )
 
 
# ----- Array에 index를 지정해서 원하는 배열 찾기(dot notation 사용)
db.inventory.find(
    {
        "dim_cm.1": { $gte: 30 }
    }
    )


# ----- Array의 length 이용해서 찾기($size operator 사용)
db.inventory.find(
    {
        tags: { $size: 3 }
    }
    )

 

4)

5)

 

3. Update Operations

Update Operation은 document를 수정할때 사용한다. update는 3가지 유형이 있다.

updateOne(), updateMany()의 경우 <update action>에 변경할 내용을 작성할때 { $set: { field: value} } 형식을 취한다.

replaceOne()의 경우 <replacement>에 변경할 내용을 작성할때 { field: value } 형식을 취한다.

3가지 경우 모두 업데이트하고자 하는 데이터가 없다면 데이터를 추가한다. replaceOne()에서는 이를 위한 parameter를 제공한다. 해당 부분은 아래 링크 참조.

#----- update operations 3가지

1. <해당db>.<해당collection>.updateOne(<update filter>, <update action>): 값 하나만 update
  가. 조건: inventory collection에서 item이 paper인 size의 uom을 cm로, status를 p로 업데이트
  나. 조건세부내용
    1) <collection>: inventory
    2) <update filter>: item이 paper인
    3) <update action>: size의 uom을 "cm"로, status를 "p"로 업데이트
  다. 조건 -> 쿼리
    db.inventory.updateOne(
        { item: "paper" },
        {
            $set: {
            
                "size.uom": "cm",
                "status": "P"
            },
            $currentDate: { lastModified: true }
        }
        )
         
    
2. <해당db>.<해당collection>.updateMany(<update filter>, <update action>): 값 여러개 update
  가. 조건: inventory collection에서 qty가 50미만인 size의 uom을 "in"으로, status를 "P"로 업데이트
  나. 조건세부내용
    1) <collection>: inventory
    2) <update filter>: qty가 50미만인
    3) <update action>: size의 uom을 "in"으로, status를 "P"로
  다. 조건 -> 쿼리
    db.inventory.updateMany(
        { "qty": { $lt: 50 } },
        {
            $set: {
                "size.uom": "in",
                status: "P"
            },
            $currentDate: { lastModified: true }
        }
        )


3. <해당db>.<해당collection>.replaceOne(<filter>, <replacement>, <options>): 값 하나만 replace
  가. 조건: inventory collection에서 item이 paper인 데이터들의 instack데이터를 업데이트
  나. 조건세부내용
    1) <collection>: inventory
    2) <filter>: item이 paper인
    3) <replacement>: instack데이터 변경
  다. 조건 -> 쿼리
    db.inventory.replaceOne(
       { item: "paper" },
       {
       		item: "paper",
            instock: [
            	{ warehouse: "A", qty: 60 },
                { warehouse: "B", qty: 40 }
            ]
        }
    	)

 

 

db.collection.replaceOne() — MongoDB Manual

Docs Home → MongoDB Manual db.collection.replaceOne(filter, replacement, options)mongosh MethodThis page documents a mongosh method. This is not the documentation for database commands or language-specific drivers, such as Node.js.For the database comman

www.mongodb.com

 

4. Delete Operations

Delete operation은 document를 삭제한다. 삭제방법은 2가지를 제공한다.

#----- delete operations 2가지

1. <db>.<collection>.deleteOne(<delete filter>): <delete filter>에 해당하는 document 하나만 삭제
  가. 조건: status가 "D"인 데이터 하나 삭제
  나. 조건 -> 쿼리
    db.inventory.deleteOne( { status: "D" } )
    
  
2. <db>.<collection>.deleteMany(<delete filter>): <delete filter>에 해당하는 document 모두 삭제
  가. 조건: status가 "D"인 데이터 모두 삭제
  나. 조건 -> 쿼리
    db.inventory.deleteMany( { status: "D" } )

 

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

Databases, Collections, Documents  (0) 2023.09.20
Intro  (0) 2023.09.20