Database/MongoDB

[MongoDB] 몽고DB의 문서(document) 저장, 수정, 삭제

gangintheremark 2023. 9. 27. 13:48
728x90

문서(document) 저장

  • _id 속성을 명시하지 않으면 자동으로 생성된다.
💡 _id는 pk 역할
 

Insert Methods — MongoDB Manual

Docs Home → MongoDB Manual MongoDB provides the following methods for inserting documents into a collection:The following methods can also add new documents to a collection:See the individual reference pages for the methods for more information and examp

www.mongodb.com

 

단일 문서 저장

db.collection.insertOne(문서)
# example

# 컬렉션이 없으면 자동으로 inventory 컬렉션이 생성된다. 
db.inventory.insertOne(
   { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)

 

멀티 문서 저장

db.collection.insertMany([문서1, 문서2, ...])
# example

db.inventory.insertMany( [
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
   { 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" },
   { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
] );

 

문서(document) 수정

 

Update Methods — MongoDB Manual

Docs Home → MongoDB Manual MongoDB provides the following methods for updating documents in a collection:Updates at most a single document that match a specified filter even though multiple documents may match the specified filter.Update all documents th

www.mongodb.com

 

단일 문서 수정

db.collection.updateOne(필터, 업데이트)
# example

# $set : 값 수정
db.inventory.updateOne({item:'paper'}, {$set:{qty:200, "size.uom":"cm"}})

# $inc : 값 증감 
db.inventory.updateOne({item:'paper'}, {$inc:{qty:-50}})

db.inventory.updateOne({item:'paper'},{$set:{status:'F'}, $inc:{qty:50}})
💡 ~. 은 쌍따옴표 "" 붙이기 ➜ "size.uom"

 

멀티 문서 수정

db.collection.updateMany(필터, 업데이트)
# example

db.inventory.updateMany({qty:{$lt:50}}, {$set:{status:'F'}})

 

문서(document) 삭제

 

MongoDB CRUD Operations — MongoDB Manual

Docs Home → MongoDB Manual CRUD operations create, read, update, and delete documents.You can connect with driver methods and perform CRUD operations for deployments hosted in the following environments:MongoDB Atlas: The fully managed service for MongoD

www.mongodb.com

 

단일 문서 삭제

db.collection.deleteOne(필터)
# example

db.inventory.deleteOne({item:'paper'})

 

멀티 문서 삭제

db.collection.deleteMany(필터)
# example

db.inventory.deleteMany({qty:{$lt:50}})
728x90