Mongodb의 CRUD

yslee·2022년 8월 20일
0
# document

{
  _id: ObjectID(),
  id: Int32,
  file_name: String,
  file_size: Double,
  tags: [String],
  resolution: {
    width: Int32,
    height: Int32,
  },
  characters: [String],
}

Create

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

1. 단일 도큐먼트 삽입

db.collection.insert(
  {
    id: 1,
    file_name: "1.jpeg",
    file_size: 245.8,
    tags: ["blue hair", "bodyshuit", "red eyes"],
    resolution: {
      width: 1191,
      height: 2048,
    },
    characters: ["Ayanami Rei"],
  }
)

2. 여러 도큐먼트 삽입

db.collection.insert(
  [
    { id: 1, ...},
	{ id: 2, ...},
	{ id: N, ...},
  ]
)

3. 여러 도큐먼트 순서 없는 삽입

db.collection.insert(
  [
    { id: 1, ...},
	{ id: 2, ...},
	{ id: N, ...},
  ],
  { ordered: false }
)

Read

1. 모든 데이터 조회

db.collection.find({})

2. name 값이 "shinji"인 doc 조회

db.collection.find({name:"shinji"})

3. name 값이 1인 doc의 name 값을 조회 (projection)

db.collection.find(
  {name:"shinji"},
  {age:1, birthDate:}
)

Update

1. update one

db.collection.updateOne(
  {id:1},
  {$set: {file_name:"1.webp", file_size:180.2}}
)

2. update many

db.collection.updateMany(
  {id:{$lte: 3}},
  {$set: {tags: null}}
)

2. replace

db.collection.replaceOne(
  {id: 1},
  {
    id: 1,
    file_name: "1.webp",
    file_size: 45.2,
    tags: ["blue hair", "bodyshuit", "red eyes"],
    resolution: {
      width: 224,
      height: 224,
    },
    characters: ["Ayanami Rei"],
  }
)

Delete

1. delete one

db.collenction.deleteOne({id:1})

2. delete many

db.collenction.deleteMany({id:{$lte: 3}})

3. delete all

db.collenction.deleteMany({})

4. delete collection (drop)

db.collenction.drop()
profile
지식보다 지혜를

0개의 댓글