파크로그

- 기존에 쓰고있던 collections ( Post - 게시글 데이터베이스 ) 에서, 게시글을 각각 지우는 것은 로직 비용이 크기에,

isDeleted 컬럼을 추가하여 사용여부를 판단하기로 결정하였다.

 

mongoDB로 기존에 쓰고있던 collections에 어떻게 field를 추가할까? 

 

> db.posts.update({}, {$set: {isDelete:false}}, false, true)
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
> db.posts.update({}, {$unset: {isDelete:false}}, false, true)
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
> db.posts.update({}, {$set: {isDeleted:false}}, false, true)
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 3 })

흐름은 다음과 같다.

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }

나처럼 특정 값에서가 아닌, 모든 object에 추가하고 싶다면 ? 

db.your_collection.update(
  {},
  { $set: {"new_field": 1} },
  false,
  true
)

3번째, 4번째 필드는 각각 upsert  multi 플래그를 지정 하는데,

 

upsert : true로 설정하면 쿼리 기준과 일치하는 문서가 없을 때 새 문서를 만든다.

multi : true로 설정하면 쿼리 기준에 맞는 여러 문서를 업데이트, false로 설정하면 하나의 문서를 업데이트

profile

파크로그

@파크park

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!