MongoDB 튜 토리 얼 의 데이터 조작 인 스 턴 스

1.  일괄 삽입:
     여러 개의 문 서 를 한 번 에 여러 개의 문 서 를 삽입 하면 한 번 의 TCP 요청 에서 완성 할 수 있 고 여러 번 요청 한 추가 비용 을 피 할 수 있 습 니 다.데이터 전 송 량 의 경우 대량으로 삽 입 된 데이터 에는 메시지 헤더 만 포함 되 어 있 고,여러 번 의 단일 삽입 은 데 이 터 를 삽입 할 때마다 메시지 헤더 데 이 터 를 봉인 합 니 다.데이터 가 져 오기 에 있어 서,우 리 는 mongoimport 를 사용 하여 완성 할 수 있 습 니 다.
 
2.  데이터베이스 지우 기:

    > db.users.remove()
 
    이상 명령 은 users 집합 에 있 는 모든 데 이 터 를 삭제 하지만 집합 자체 와 관련 된 색인 은 삭제 하지 않 습 니 다.데이터 삭제 작업 은 복구 할 수 없 으 며 삭제 되면 물리 적 으로 삭 제 됩 니 다.전체 집합 에서 이러한 케이스 를 제거 하 는 데 더욱 효과 적 인 방법 은 집합 대상 자체 와 그 와 관련 된 모든 색인 을 직접 삭제 한 다음 에 순서대로 재 구축 하 는 것 이다.예 를 들 어:
 

    > db.one_collection.drop()
 
 
3.  데이터 업데이트: 
    데이터 업 데 이 트 를 실행 할 때 업데이트 조건 과 일치 하 는 문서 가 여러 개 있 습 니 다.업 데 이 트 된 을 피하 기 위해 서 입 니 다.id 에 중복 충돌 이 발생 하면 MongoDB 는 첫 번 째 조회 결과 만 업데이트 합 니 다.예 를 들 어:
 

    > post1 = { "name": "stephen", "age" : "35"}
    { "name" : "stephen", "age" : "35" }
    > post2 = { "name": "stephen", "age" :  36}
    { "name" : "stephen", "age" : 36 }
    > db.blog.insert(post1)
    > db.blog.insert(post2)
    > post3 = { "name" : "stephen", "age": 37}
    { "name" : "stephen", "age" : 37 }
    > db.blog.update({"name":"stephen"},post3)
    > db.blog.find()
    { "_id" : ObjectId("4fcd7e2e20668578cc1097d8"), "name" : "stephen", "age" : 36 }
    { "_id" : ObjectId("4fcd7e2820668578cc1097d7"), "name" : "stephen", "age" : 37 }
 
 
4.  수정 기:
    수정 기 를 사용 하여 데이터 업 데 이 트 를 하 는 것 은 원자 이 고 효율 적 이 며 모든 문서 와 달리 업 데 이 트 된 문서 의id 는 변 하지 않 고 문서 가 완전히 업데이트 되면 문 서 를 수정 합 니 다id 및 관련 색인.
  

 > db.blog.find()
    { "_id" : ObjectId("4fcd7e2820668578cc1097d7"), "name" : "stephen", "age" : 41 }
    { "_id" : ObjectId("4fcd81bb20668578cc1097d9"), "name" : "stephen", "age" : 38 }
    --$inc age , 。
    > db.blog.update({"name":"stephen"},{"$inc":{"age":1}}) 
    > db.blog.find()
    { "_id" : ObjectId("4fcd7e2820668578cc1097d7"), "name" : "stephen", "age" : 42 }
    { "_id" : ObjectId("4fcd81bb20668578cc1097d9"), "name" : "stephen", "age" : 38 }
    -- update , :
    > db.blog.update({"name":"stephen"},{"$inc":{"age":1}},true,true)
    > db.blog.find()
    { "_id" : ObjectId("4fcd7e2820668578cc1097d7"), "name" : "stephen", "age" : 43 }
    { "_id" : ObjectId("4fcd81bb20668578cc1097d9"), "name" : "stephen", "age" : 39 }

    --$set , , 。
    > db.blog.update({"name":"stephen"},{"$set":{"genda":"male"}})
    > db.blog.find()
    { "_id" : ObjectId("4fcd88b720668578cc1097da"), "age" : "35", "genda" : "male", "name" : "stephen" }
    --$unset $set , :
    > db.blog.update({"name":"stephen"},{"$unset":{"genda":"male"}})
    > db.blog.find()
    { "_id" : ObjectId("4fcd88b720668578cc1097da"), "age" : "35", "name" : "stephen" }
    -- $set 。
    > db.blog.find()
    { "_id" : ObjectId("4fcd8e0220668578cc1097db"), "title" : "A Blog Post", "author" : { "name" : "joe", "email" : "[email protected]" } }
    > db.blog.update({"title":"A Blog Post"},{"$set":{"author.name":"joe schmoe"}})
    > db.blog.find()
    { "_id" : ObjectId("4fcd8e0220668578cc1097db"), "author" : { "email" : "[email protected]", "name" : "joe schmoe" }, "title" : "A Blog Post" }

 
5.  배열 수정 기:

    > db.blog.insert({"title":"one blog"})
    > db.blog.find()
    { "_id" : ObjectId("4fcd909520668578cc1097dc"), "title" : "one blog" }
    -- , , 。
    > log.update({"title":"one blog"}, {"$push": {"comments":{"content":"hello"}}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fcd909520668578cc1097dc"),
         "comments" : [
                 {
                         "content" : "hello"
                 }
         ],
         "title" : "one blog"
    }
    -- $push , , 。
    > db.blog.update({"title":"one blog"}, {"$push": {"comments":{"content":"word"}}
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fcd909520668578cc1097dc"),
         "comments" : [
                 {
                         "content" : "hello"
                 },
                 {
                         "content" : "word"
                 }
         ],
         "title" : "one blog"
    }
 
    > post = {"username":"joe", "emails":["[email protected]","[email protected]","[email protected]"]}
    {
         "username" : "joe",
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ]
    }
    > db.blog.insert(post)
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "username" : "joe",
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ]
    }
    --$addToSet , , , 。
    > db.blog.update({"username":"joe"}, {"$addToSet": {"emails":"[email protected]"}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "username" : "joe",
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ]
    }
    > db.blog.update({"username":"joe"}, {"$addToSet": {"emails":"[email protected]"}
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ],
         "username" : "joe"
    }
    --$addToSet $each 。
    > db.blog.update({"username":"joe"},{"$addToSet": {"emails":{"$each":["[email protected]","[email protected]"]}}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ],
         "username" : "joe"
    }
    --$pop , 1, , -1, 。
    > db.blog.update({"username":"joe"}, {"$pop":{"emails":1}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ],
         "username" : "joe"
    }
    > db.blog.update({"username":"joe"}, {"$pop":{"emails":-1}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ],
         "username" : "joe"
    }
    --$pull
    > db.blog.update({"username":"joe"}, {"$pull":{"emails":"[email protected]"}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "emails" : [
                 "[email protected]",
                 "[email protected]"
         ],
         "username" : "joe"
    }
    -- , 。
    > db.blog.update({"username":"joe"}, {"$push": {"emails":"[email protected]"}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ],
         "username" : "joe"
    }
    -- , 0, 。 1
    --( ) 。
    > db.blog.update({"username":"joe"}, {"$set":{"emails.1":"[email protected]"}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ],
         "username" : "joe"
    }
    -- , , ,MongoDB
    -- $ 。 。
    > db.blog.update({"emails":"[email protected]"},{"$set":{"emails.$":"[email protected]"}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2e468b2ac404941134bed"),
         "emails" : [
                 "[email protected]",
                 "[email protected]",
                 "[email protected]"
         ],
         "username" : "joe"
   }
 
6.  upsert:
    upsert 는 특수 한 업데이트 입 니 다.업데이트 조건 에 맞 는 문서 가 없 으 면 이 조건 과 업데이트 문 서 를 바탕 으로 새 문 서 를 만 듭 니 다.일치 하 는 문 서 를 찾 으 면 정상적으로 업 데 이 트 됩 니 다.
   

 > db.blog.remove()
    > db.blog.update({"username":"joe"},{"username":"joe","age":30},true)
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fd2faac576cd9c101ac0f3d"),
         "username" : "joe",
         "age" : 30
    }
 
    아래 의 예 는 새로 추 가 된 동시에 새로 추 가 된 값 을 수정 할 수 있다.
 

    > db.blog.remove()
    > db.blog.update({"count":25},{"$inc":{"count":3}},true)
    > db.blog.find()
    { "_id" : ObjectId("4fd2fd59576cd9c101ac0f3e"), "count" : 28 }
 
    save 는 셸 함수 로 문서 가 존재 하지 않 을 때 삽입 하고 존재 할 때 업데이트 할 수 있 습 니 다.upsert 도 같은 일 을 할 수 있 지만 save 명령 보다 편리 합 니 다.
 

    > var x = db.blog.findOne()
    > x.count = 40
    40
    > db.blog.save(x)
    > db.blog.findOne()
    { "_id" : ObjectId("4fd2fde4576cd9c101ac0f3f"), "count" : 40 }
 
7.  업 데 이 트 된 문 서 를 되 돌려 줍 니 다:
    getLastError 명령 을 통 해 여러 문 서 를 업데이트 할 때 업 데 이 트 된 문서 의 수 를 가 져 올 수 있 습 니 다.
 

    > db.blog.remove()
    > db.blog.insert({"name":"stephen"})
    > db.blog.insert({"name":"stephen3"})
    > db.blog.insert({"name":"stephen4"})
    > db.blog.update({},{"$set":{"name":"liu"}},false,true)
    --n:3 3。
    > db.runCommand({getLastError:1})
    {
        "updatedExisting" : true,
        "n" : 3,
        "connectionId" : 1,
        "err" : null,
        "ok" : 1
    }
 
    findAndModify 는 검색 결 과 를 원자 적 으로 수정 할 수도 있 고,검색 결 과 를 원자 적 으로 삭제 할 수도 있다.
 

    > db.blog.insert({"name":"stephen"})
    > db.blog.insert({"name":"stephen2"})
    > db.blog.find()
    { "_id" : ObjectId("4fd30cd117f6dccb7c058244"), "name" : "stephen" }
    { "_id" : ObjectId("4fd30cd417f6dccb7c058245"), "name" : "stephen2" }        
    > db.runCommand({"findAndModify":"blog", "query":{"name":"stephen2"},"update":{"$set":{"name":"stephen3"}}})
    > db.blog.find()
    { "_id" : ObjectId("4fd30cd117f6dccb7c058244"), "name" : "stephen" }
    { "_id" : ObjectId("4fd30cd417f6dccb7c058245"), "name" : "stephen3" }
    > runCommand({"findAndModify":"blog", "query":{"name":"stephen3"},"remove":true})
    > db.blog.find()
    { "_id" : ObjectId("4fd30cd117f6dccb7c058244"), "name" : "stephen" }
 
    findAndModify 명령 의 키 마다 대응 하 는 값 은 다음 과 같 습 니 다.
    findAndModify:문자열 형식의 집합 이름 입 니 다.
    query:문 서 를 검색 하 는 조건 으로 문 서 를 조회 합 니 다.
    sort:결 과 를 정렬 하 는 조건 입 니 다.
    update:문 서 를 수정 하고 찾 은 문 서 를 업데이트 합 니 다.
    reove:불 형식,문서 삭제 여 부 를 표시 합 니 다.
    new:불 형식 은 업데이트 전 문 서 를 되 돌려 주 는 것 입 니까?업데이트 후 문 서 를 되 돌려 주 는 것 입 니까?결 성 은 업데이트 전 문서 입 니 다.
    update 와 reove 는 하나의 존재 가 있어 야 하고 하나의 존재 만 있 을 수 있 습 니 다.일치 하 는 문서 가 없 으 면 이 명령 은 오 류 를 되 돌려 줍 니 다.이 명령 은 한 번 에 하나의 문서 만 처리 할 수 있 고 upsert 작업 을 수행 할 수 없 으 며 기 존 문서 만 업데이트 할 수 있 습 니 다.

좋은 웹페이지 즐겨찾기