카테고리 없음

mongodb 간단하게 해보기.

머룽 2023. 4. 21. 15:26
설치는 인터넷이 자세히 나와 있으니 참고 하길 바란다. 맥 경우에는 brew으로 간편하게 설치도 가능하니 참고하길 바란다. https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/ 우리는 간단하게 커멘드 창에서 CUD를 해보겠다. 몽고 서버와 몽고 클라이언트를 실행시키자. select는 공부할게 많으니 나중에 다시 해보겠다.

insert

> db.user.insert({ name: "wonwoo", age : 27, email: "test@test.com" } )
WriteResult({ "nInserted" : 1 })
nosql 이니 json으로 들어간다.
> db.user.insertOne({ name: "wonwoo1", age : 20, email: "test1@test.com" } )
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5767f41228dcf51e4b235173")
}
insertOne 도 insert가 가능하다. 다른점은 잘 모르겠다. 리턴이 다른건 확인이 가능한데.. 흠..
> db.user.insertMany([
  { name: "wonwoo2", age : 22, email: "test2@test.com"}, 
  { name: "wonwoo3", age : 32, email: "test3@test.com"}, 
  { name: "wonwoo4", age : 37, email: "test4@test.com"}])

{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5767f58128dcf51e4b235174"),
        ObjectId("5767f58128dcf51e4b235175"),
        ObjectId("5767f58128dcf51e4b235176")
    ]
}
다중 insert도 가능하다. insertMany를 이용하면 된다.

update

몽고 사이트에서 예제로 있는 것을 해보자.
db.users.insertMany(
   [
     {
       _id: 1,
       name: "sue",
       age: 19,
       type: 1,
       status: "P",
       favorites: { artist: "Picasso", food: "pizza" },
       finished: [ 17, 3 ],
       badges: [ "blue", "black" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 85, bonus: 10 }
       ]
     },
     {
       _id: 2,
       name: "bob",
       age: 42,
       type: 1,
       status: "A",
       favorites: { artist: "Miro", food: "meringue" },
       finished: [ 11, 25 ],
       badges: [ "green" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 64, bonus: 12 }
       ]
     },
     {
       _id: 3,
       name: "ahn",
       age: 22,
       type: 2,
       status: "A",
       favorites: { artist: "Cassatt", food: "cake" },
       finished: [ 6 ],
       badges: [ "blue", "Picasso" ],
       points: [
          { points: 81, bonus: 8 },
          { points: 55, bonus: 20 }
       ]
     },
     {
       _id: 4,
       name: "xi",
       age: 34,
       type: 2,
       status: "D",
       favorites: { artist: "Chagall", food: "chocolate" },
       finished: [ 5, 11 ],
       badges: [ "Picasso", "black" ],
       points: [
          { points: 53, bonus: 15 },
          { points: 51, bonus: 15 }
       ]
     },
     {
       _id: 5,
       name: "xyz",
       age: 23,
       type: 2,
       status: "D",
       favorites: { artist: "Noguchi", food: "nougat" },
       finished: [ 14, 6 ],
       badges: [ "orange" ],
       points: [
          { points: 71, bonus: 20 }
       ]
     },
     {
       _id: 6,
       name: "abc",
       age: 43,
       type: 1,
       status: "A",
       favorites: { food: "pizza", artist: "Picasso" },
       finished: [ 18, 12 ],
       badges: [ "black", "blue" ],
       points: [
          { points: 78, bonus: 8 },
          { points: 57, bonus: 7 }
       ]
     }
   ]
)
업데이트를 해보자.
> db.users.updateOne(
...    { "favorites.artist": "Picasso" },
...    {
...      $set: { "favorites.food": "pie", type: 3 },
...      $currentDate: { lastModified: true }
...    }
... )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
favorites 안에 artist의 명이 Picasso인 것을 favorites.foods는 pie로 바꾸고 type은 3으로 업데이틀 한다. 그리고 lastModified를 현재 시간으로 업데이트 한다.
> db.users.findOne({"_id" : 1})
{
    "_id" : 1,
    "name" : "sue",
    "age" : 19,
    "type" : 3,
    "status" : "P",
    "favorites" : {
        "artist" : "Picasso",
        "food" : "pie"
    },
    "finished" : [
        17,
        3
    ],
    "badges" : [
        "blue",
        "black"
    ],
    "points" : [
        {
            "points" : 85,
            "bonus" : 20
        },
        {
            "points" : 85,
            "bonus" : 10
        }
    ],
    "lastModified" : ISODate("2016-06-20T14:04:50.252Z")
}
findOne으로 아이디가 1인것을 찾으면 이렇게 업데이트가 되어 있다. 근데 이상하다 id가 6인 것도 favorites.artist 똑같이 Picasso 인데 업데이트 되지 않았다. 모두다 업데이트 하고 싶다면 updateMany를 사용하면 된다.
> db.users.updateMany(
...    { "favorites.artist": "Picasso" },
...    {
...      $set: { "favorites.artist": "Pisanello", type: 3 },
...      $currentDate: { lastModified: true }
...    }
... )
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
modifiedCount가 2인 것을 확인할 수 있다. 다시 확인 해보자.
> db.users.findOne({"_id" : 6})
{
    "_id" : 6,
    "name" : "abc",
    "age" : 43,
    "type" : 3,
    "status" : "A",
    "favorites" : {
        "food" : "pizza",
        "artist" : "Pisanello"
    },
    "finished" : [
        18,
        12
    ],
    "badges" : [
        "black",
        "blue"
    ],
    "points" : [
        {
            "points" : 78,
            "bonus" : 8
        },
        {
            "points" : 57,
            "bonus" : 7
        }
    ],
    "lastModified" : ISODate("2016-06-20T14:15:04.696Z")
}
아디디가 6인 것도 변경 되었다.

delete

delete 도 간단하다.
> db.users.deleteOne( { status: "D" } )
{ "acknowledged" : true, "deletedCount" : 1 }
deleteOne을 이용하여 status 가 "D" 인 것을 삭제 하였다. update와 마찬가지로 처음 나오는 것만 삭제하고 나머지는 삭제 하지 않는다. 모두 삭제 하고 싶다면 아래와 같이 deleteMany를 이용하면 된다.
> db.users.deleteMany({ status : "A" })
{ "acknowledged" : true, "deletedCount" : 3 }
deleteMany를 이용하여 status가 "A"인 것을 모두 삭제 하였다.
db.users.find()
위와 같이 find()를 이용하여 확인해보면 status가 "A"인 것은 모두 삭제 되었다.
> db.users.remove({})
WriteResult({ "nRemoved" : 6 })

> db.users.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 6 }
remove와 deleteMany를 이용하여 모두 삭제 할 수 있다. 이것 역시 다른 점이 있다면 리턴타입이 다르다. 그 이외는 잘 모르겠다. 현재 진행한 CUD 말고 API가 몇개 더 있지만 자주 사용하는 것만 작성했다. 더 궁금하다면 레퍼런스를 참고 하길 바란다. 다음시간에는 select의 대해서 알아보자. 뭘 하든 select는 양이 많으니 .... 이상하게 위의 update 데이터중 커멘드 창에서 6개를 한꺼번에 넣으니까 에러가 발생한다. 커멘드라 찾기도 귀찮아서 나눠서 넣었다. 예제 )
db.users.insertMany(
   [
     {
       _id: 1,
       name: "sue",
       age: 19,
       type: 1,
       status: "P",
       favorites: { artist: "Picasso", food: "pizza" },
       finished: [ 17, 3 ],
       badges: [ "blue", "black" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 85, bonus: 10 }
       ]
     },
     {
       _id: 2,
       name: "bob",
       age: 42,
       type: 1,
       status: "A",
       favorites: { artist: "Miro", food: "meringue" },
       finished: [ 11, 25 ],
       badges: [ "green" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 64, bonus: 12 }
       ]
     },
     {
       _id: 3,
       name: "ahn",
       age: 22,
       type: 2,
       status: "A",
       favorites: { artist: "Cassatt", food: "cake" },
       finished: [ 6 ],
       badges: [ "blue", "Picasso" ],
       points: [
          { points: 81, bonus: 8 },
          { points: 55, bonus: 20 }
       ]
     }
  ]
)
db.users.insertMany(
   [
     {
       _id: 4,
       name: "xi",
       age: 34,
       type: 2,
       status: "D",
       favorites: { artist: "Chagall", food: "chocolate" },
       finished: [ 5, 11 ],
       badges: [ "Picasso", "black" ],
       points: [
          { points: 53, bonus: 15 },
          { points: 51, bonus: 15 }
       ]
     },
     {
       _id: 5,
       name: "xyz",
       age: 23,
       type: 2,
       status: "D",
       favorites: { artist: "Noguchi", food: "nougat" },
       finished: [ 14, 6 ],
       badges: [ "orange" ],
       points: [
          { points: 71, bonus: 20 }
       ]
     },
     {
       _id: 6,
       name: "abc",
       age: 43,
       type: 1,
       status: "A",
       favorites: { food: "pizza", artist: "Picasso" },
       finished: [ 18, 12 ],
       badges: [ "black", "blue" ],
       points: [
          { points: 78, bonus: 8 },
          { points: 57, bonus: 7 }
       ]
     }
   ]
)