오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-03 06:06
관리 메뉴

우노

[MongoDB] CRUD 본문

Database/MongoDB

[MongoDB] CRUD

운호(Noah) 2020. 7. 3. 13:17

Create/Read/Update/Delete Operations

Insert

db.collection.insertOne(
    { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ], status: "D" },
)
db.collection.insertMany([

{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ], status: "D" },

{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ], status: "A" },

{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ], status: "D" },

{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }

])

Read

db.collection.find()
db.collection.find({})

skip ( 상위 몇개 생략하기 )

db.collection.find().skip(2)

Limit ( 몇개까지 나타낼건지 )

db.collection.find({}).limit(2)

Sort

// qty 키를 오름차순 정렬
db.collection.find().sort({"qty":1})
// qty 키를 내림차순 정렬
db.collection.find().sort({"qty":-1})

findOne ( 첫 번째 도큐먼트 가져오기 )

db.collection.findOne({})

find

db.collection.find({ status : "A" })

findOne

db.collection.findOne({ status : "A" })

Update

db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()

단일 업데이트

  • collection, filter, action 순으로 진행된다.

      db.collection.updateOne(
        { status : "A" },
      { $set: { qty : 200 }} 
      )
    

다중 업데이트

db.collection.updateMany(
{ qty : { $lt : 100 } },
{ $set: { status : "P" }} 
)

replaceOne

db.collection.replaceOne( 
<filter>,
<replacement> 
)

도큐먼트를 가져와서 객체로 다루고 업데이트!

obj_id = ObjectId("5ee0274608eefd0171a4fbae")
doc = db.collection.findOne({"_id" : obj_id})
doc['item'] = "e-mail"
doc['qty'] = 120

db.collection.update({ _id : obj_id}, doc )
db.collection.find()

배열 안에 set 추가하기 ( 배열이 아니라면 오류 발생! )

db.collection.update (
    { qty : {$lte : 80} },
    { $addToSet : {tags: "white"} } 
) 

해당 값을 증가시켜준다.

db.collection.update ( 
    { item : "paper" },
    { $inc : { qty : 1000 } }
)

Delete

db.inventory.deleteOne( { status : "A" } )
db.inventory.deleteMany( { status : "P" } )
db.inventory.deleteMany( { } )

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

[MongoDB] Condition  (0) 2020.07.03
[MongoDB] ArrayElement  (0) 2020.07.03
[MongoDB] Projection  (0) 2020.07.03
[MongoDB] Cursor  (0) 2020.07.03
[MongoDB] Aggregation  (0) 2020.07.03
Comments