2011년 5월 21일 토요일

Vagant

Vagant

  • 개요: 가상머신을 쉽게 사용하게 해주는 도구
  • 공식 사이트 Vagrant
  • 지식 : UNIX, Ruby
  • 도구 : Vagrant , VirtualBox / VMware / EC2
  • 확인
vagrant —version
Vagrant 1.6.2

가상머신

  • Box (템플릿) 을 구하자.
  • 가상머신 초기화
  • 가상머신 부팅.
  • Box 입수
    vargrant box add precise32 \
    http://files.vagrantup.com/precise32.box
  • 리스트를 보자.
    vagrant box list
  • Box를 지워보자
    vagrant box remove precise32
  • Box는 템플릿으로 이것을 가지고 여러개의 가상 머신으로 확장이 가능하다.
  • 다시말하면 1 Box로 여러개의 다른 가상 머신을 만들어 사용할 수 있다.

가상머신을 만들어 보자.

  • CentOS64를 이용해 보자.
  • 우선 템플릿을 받는다.
  • 초기화를 한다.
> vagrant box init centos64
vagrant init centos64
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.
  • Vagrantfile을 정보를 확인해 보자.
    less Vagrantfile
  • Vagrantfile 이 있는 폴더에서 실행한다.
    vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos64'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: myCentOSVM_default_1400596418688_49507
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/mscho/Simon/vagrant/myCentOSVM

가상 머신의 정지, 재기동, 소거

  • status 상태를 본다.
  • suspend 잠자기에서 깨어난다.
  • halt 중지 시킨다.
  • up 기동 시킨다.
  • reload 재시동 시킨다.
  • destory 가상머신을 지운다.

status

vagrant status
Current machine states:

default                   running (virtualbox)

The VM is running. To stop this VM, you can run `vagrant halt` to
shut it down forcefully, or you can run `vagrant suspend` to simply
suspend the virtual machine. In either case, to restart it again,
simply run `vagrant up`.

suspend

> vagrant suspend
==> default: Saving VM state and suspending execution...

resume

> vagrant resume
==> default: Resuming suspended VM...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection refused. Retrying...
==> default: Machine booted and ready!

destroy

vagrant destroy
    default: Are you sure you want to destroy the 'default' VM? [y/N] Y
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...

가상 머신을 접속해 보자.

  • 부팅한 이후에 ssh로 접속해 보자.
    vagrant up
    vagrant ssh
  • http 서버를 설치해 보자.
    sudo yum -y install httpd
  • http 서버를 동작 시키자.
    sudo service httpd start
    sudo chkconfig httpd on
  • 방화벽을 꺼보자.
    sudo service iptables stop
    sudo chkconfig iptables off

웹페이지를 만들고 접속해 보자.

cd /var/www/html
sudo vi index.html
<h1> hello world. </h1>
  • 네트워크 설정을 위해서 빠져 나가자.
    exit
  • Vagrantfile 을 편집해서 네트워크를 설정하자.
    emacs Vagrantfile
    config.vm.network “private_network”, ip: “192.168.33.10”
  • 저장한후 reload하자.
    vagrant reload

공유 폴더를 사용해 보자.

  • 호스트의 Vagrantfile이 있는 폴더가 공유 폴더가 된다.
  • 가상머신은 /vagrant 폴더가 공유 폴더가 된다.
  • 예제로 호스트에서 index.html을 수정해서 가상 머신의 웹서비스로 보자.

가상 머신에서 공유 폴더 설정

vagrant ssh
sudo rm -fr /var/www/html
sudo ln -fs /vagrant /var/www/html
exit

호스트에서 index.html을 만들고, 브라우져로 가상 머신에 접속해 보자.

emacs index.html
<h1> hello world from OS X </h1>

Provisioning 을 사용해 보자.

  • 정의 : Vargant up이후 자동적으로 실행되는 처리를 말한다.
  • 새로운 provision용 vm을 만들자
    mkdir myOS
    cd myOS
    vagrant init centos64
  • provision 설정을 해 보자
    emacs VagrantFile
    config.vm.provision :shell, :inline => “echo hello world”
  • 설정한 vm을 동작시켜 보자.
vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos64'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: myCentOSVM2_default_1400599326027_6547
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/mscho/Simon/vagrant/myCentOSVM2
==> default: Running provisioner: shell...
    default: Running: inline script
==> default: hello world
  • 마지막에 hello world가 나타나는 것을 알수 있다.

좀더 세밀한 프로비전을 해 보자.

  • Vagrantfile을 열어서 설정을 바꿔 준다.
    config.vm.provision :shell, :path => “provision.sh”
sudo yum -y install httpd
sudo service httpd start
sudo chkconfig httpd on
sudo service iptables stop
sudo chkconfig iptables off
  • 설정한 프로비전을 적용해 보자.
    vagrant provision
  • 프로비전에 맞게 웹서비스가 올라가 있는지 확인해 보자.
    vagrant ssh
    sudo service httpd status
    httpd (pid 2121) is running…

자신만의 Box를 만들어 보자.

  • 동작하는 vm으로 만들어 보자.
    vagrant package
  • 만들어진 box를 확인해 보자.
    ls
    Vagrantfile package.box provision.sh
  • 만들어진 box를 새로운 템플릿으로 추가해 보자.
    vagrant box add my_box package.box
    ==> box: Adding box 'my_box' (v0) for provider: 
       box: Downloading: file:///Users/Simon/vagrant/myCentOSVM2/package.box
    ==> box: Successfully added box 'my_box' (v0) for 'virtualbox'!
    
  • 추가된 템플릿을 확인해 보자.
    ls ~/.vagrant.d/boxes/
    centos64 my_box precise32
  • 새로 추가된 템플릿으로 vm을 동작시켜 보자.
    cd ..
    mkdir myBox
    cd myBox
    vagrant init my_box
    vagrant up
    vagrant ssh
    sudo service httpd status
    httpd (pid 1391) is running…

plugin을 사용해 보자.

  • 여러가지 plugin이 있다.
    vagrant plugin install sahara
Installing the 'sahara' plugin. This can take a few minutes...
Building nokogiri using packaged libraries.
Building libxml2-2.8.0 for nokogiri with the following patches applied:
    - 0001-Fix-parser-local-buffers-size-problems.patch
    - 0002-Fix-entities-local-buffers-size-problems.patch
    - 0003-Fix-an-error-in-previous-commit.patch
    - 0004-Fix-potential-out-of-bound-access.patch
    - 0005-Detect-excessive-entities-expansion-upon-replacement.patch
    - 0006-Do-not-fetch-external-parsed-entities.patch
    - 0007-Enforce-XML_PARSER_EOF-state-handling-through-the-pa.patch
    - 0008-Improve-handling-of-xmlStopParser.patch
    - 0009-Fix-a-couple-of-return-without-value.patch
    - 0010-Keep-non-significant-blanks-node-in-HTML-parser.patch
    - 0011-Do-not-fetch-external-parameter-entities.patch
************************************************************************
IMPORTANT!  Nokogiri builds and uses a packaged version of libxml2.

If this is a concern for you and you want to use the system library
instead, abort this installation process and reinstall nokogiri as
follows:

    gem install nokogiri -- --use-system-libraries

If you are using Bundler, tell it to use the option:

    bundle config build.nokogiri --use-system-libraries
    bundle install

However, note that nokogiri does not necessarily support all versions
of libxml2.

For example, libxml2-2.9.0 and higher are currently known to be broken
and thus unsupported by nokogiri, due to compatibility problems and
XPath optimization bugs.
************************************************************************
************************************************************************
Building libxslt-1.1.28 for nokogiri with the following patches applied:
    - 0001-Adding-doc-update-related-to-1.1.28.patch
    - 0002-Fix-a-couple-of-places-where-f-printf-parameters-wer.patch
    - 0003-Initialize-pseudo-random-number-generator-with-curre.patch
    - 0004-EXSLT-function-str-replace-is-broken-as-is.patch
    - 0006-Fix-str-padding-to-work-with-UTF-8-strings.patch
    - 0007-Separate-function-for-predicate-matching-in-patterns.patch
    - 0008-Fix-direct-pattern-matching.patch
    - 0009-Fix-certain-patterns-with-predicates.patch
    - 0010-Fix-handling-of-UTF-8-strings-in-EXSLT-crypto-module.patch
    - 0013-Memory-leak-in-xsltCompileIdKeyPattern-error-path.patch
    - 0014-Fix-for-bug-436589.patch
    - 0015-Fix-mkdir-for-mingw.patch
************************************************************************
IMPORTANT!  Nokogiri builds and uses a packaged version of libxslt.

If this is a concern for you and you want to use the system library
instead, abort this installation process and reinstall nokogiri as
follows:

    gem install nokogiri -- --use-system-libraries

If you are using Bundler, tell it to use the option:

    bundle config build.nokogiri --use-system-libraries
    bundle install
************************************************************************
Installed the plugin 'sahara (0.0.16)'!
vagrant plugin -h
Usage: vagrant plugin <command> [<args>]

Available subcommands:
     install
     license
     list
     uninstall
     update

For help on any individual command run `vagrant plugin COMMAND -h`
vagrant plugin list
sahara (0.0.16)
vagrant-login (1.0.1, system)
vagrant-share (1.0.1, system)
$ vagrant plugin uninstall sahara
Uninstalling the 'sahara' plugin...
$ vagrant plugin list      
vagrant-login (1.0.1, system)
vagrant-share (1.0.1, system)

sahara를 사용해 보자.

  • sahara 플러그 인은 sanabox를 지원해 준다.
  • sandbox는 vm에 프로그램을 설치하거나 변경했는데, 이것을 되돌릴때 사용
vagrant sandbox on
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
vagrant ssh
touch test
ls
test
exit
  • 되돌려 보자.
vagrant sandbox rollback
vagrant ssh
ls
exit
  • 샌드 박스 커밋을 사용해서 확정하여 관리해 보자.
  • vm동작중에는 시간이 많이 걸리므로 잠재운다.
vagrant suspend
==> default: Saving VM state and suspending execution...
vagrant sandbox commit
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
  • sandbox를 중지해 보자.
sandbox status
[default] Sandbox mode is on
vagrant sandbox off
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
vagrant sandbox status
[default] Sandbox mode is off vagrant sandbox off

2011년 5월 20일 금요일

MongoDB

MongoDB

  • 개요
  • 문서 위주의 데이터 베이스
  • NoSQL (cf. MySQL RDB), schema-less
  • 공식 사이트 MongoDB.org
  • 필요 지식
    • 유닉스 명령어 : Unix CLI
    • 자바스크립트 : JavaScript
    • 정규표현식 : Regular Expressing
    • 로컬개발 환경 Vagrant
    • 사용 버전
      mongo —version
      MongoDB shell version: 2.6.0

용어 정리

  • 데이터 베이스 아래, 콜렉션(Collection)이 있고, 그 아래 문서(Document)가 있다.
MySQLMongoDB
Databasedatabase
TableCollection
RecordDocuement
  • Document는 JavaScript로 처리하며 key:val로 구성된다.
  • schema-less 이므로 기존 RBD처럼 Docuemnt가 고정되지 않는다.
  • 예를 들면
    • hephaex는 name, score 의 키값을 가지지만
    • foo는 name, score,team을 가진다.
  • Database : BlogApp
    • Collection : Posts
      • Document
      • Document
      • Document
    • Collection : Users
      • Document
         {key:val, key:val, ... , key:val}
        
      • Document
         {name:"hephaex", score: 100, ... , key:val}
        
      • Document
         {name:"foo", score: 90, team:3, ..., key:val }
        

Database

  • show dbs; 데이터 베이스 리스트
  • use _ ; 신규작성, 전환
  • db.drobDatabase() ; 제거
    mongo mydb
    MongoDB shell version: 2.6.0
    connecting to: mydb
  • exit : 빠져나가기
  • help : 도움말
  • show dbs; // 데이터 베이스 보기
    admin (empty)
    local 0.078GB
  • 콜렉션을 생성해 보자.
    db.createCollection(‘test’);
    { “ok” : 1 }
  • 생성된 콜렉션을 확인해 보자
    show dbs;
    admin (empty)
    local 0.078GB
    mydb 0.078GB
  • 데이터 베이스를 바꿔보자.
    use mydb2
    switched to db mydb2
  • 주의할 점은 mydb2를 콜렉션으로 만들지 않았기 때문에 show dbs하면 mydb만 나온다.
    즉 생성되지 않은 것이라서 내용이 바뀌지 않는다.
  • 데이터 베이스를 지워보자.
use mydb
switched to db mydb
db.dropDatabase();
{ “dropped” : “mydb”, “ok” : 1 }
show dbs;
admin (empty)
local 0.078GB
  • mydb가 삭제된 것을 학인할 수 있다.

콜렉션을 다뤄보자.

  • db.createCollection(‘col’); 새로 만들기
  • show collections; 콜렉션 목록 보기
  • db._.renameCollection(‘newCol’); 이름 바꾸기
  • db._.drop(); 콜렉션 지우기

example)

  • 우선 mydb로 바꾸고 데이터 베이스가 있는지 확인해 보자.
use mydb;
switched to db mydb
show dbs;
admin (empty)
local 0.078GB
  • 콜렉션 users를 생성해 보자.
db.createCollection(‘users’);
{ “ok” : 1 }
  • 생성된 users 콜렉션을 확인해 보자.
show collections;
system.indexes
users
  • users 콜렉션을 person으로 바꿔보자.
db.users.renameCollection(‘person’);
{ “ok” : 1 }
show collections
person
system.indexes
  • 콜렉션 person을 지워보자.
db.person.drop();
true
show collections;
system.indexes

도규먼트를 다뤄보자.

  • db.COL.insert(); 새로 만들기
  • db.COL.find(); 전부 검색하기
  • db.COL.remove(); 지우기
  • db.COL.count(); 갯수

example)

  • 데이터 베이스를 확인해 보자.
show dbs;
admin (empty)
local 0.078GB
mydb 0.078GB
  • mydb 데이터 베이스를 선택하고 콜렉션을 확인하자.
use mydb;
switched to db mydb
show collections
system.indexes
  • users라는 콜렉션을 생성하고 데이터를 넣자.
db.createCollection(‘users’);
{ “ok” : 1 }
db.users.insert({name:”hephaex”, score:100});
WriteResult({ “nInserted” : 1 })
db.users.insert({name:”foo”, tags:[“web”,”mobile”]});
WriteResult({ “nInserted” : 1 })
  • 여기서 foo는 NoSQL이기 때문에 스키마를 배열로 넣을 수 있다. (*)
  • users 콜렉션에 어떤것이 들어 있는지 확인해 보자.
db.users.find();
{ “_id” : ObjectId(“537ab7e83cba50cc281a7e92”), “name” : “hephaex”, “score” : 100 }
{ “_id” : ObjectId(“537ab8243cba50cc281a7e93”), “name” : “foo”, “tags” : [ “web”, “mobile” ] }
  • 도큐먼트 수를 헤아려 보자.
db.users.count();
2
  • 도큐먼트를 삭제해 보자.
db.users.find();
{ “_id” : ObjectId(“537ab7e83cba50cc281a7e92”), “name” : “hephaex”, “score” : 100 }
{ “_id” : ObjectId(“537ab8243cba50cc281a7e93”), “name” : “foo”, “tags” : [ “web”, “mobile” ] }
삭제되지 않는것에 주의할 것.
db.users.remove();
2014-05-20T11:21:46.681+0900 remove needs a query at src/mongo/shell/collection.js:299
지우려면 remove({})를 사용해야 document가 지워진다.
db.users.remove({});
WriteResult({ “nRemoved” : 2 })

자바스크립트로 데이터를 넣어보자.

  • MongoDB는 자바스크립트를 바로 쓸수 있다.
    for (var i = 0; i < 4; i++) {
    db.users.insert({
      name : "user-" + i,
      team : "team-" + (i % 3),
      score : Math.floor(Math.random() * 100)
      });
    }
    
    db.users.find()
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e94”), “name” : “user-0”, “team” : “team-0”, “score” : 51 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “name” : “user-1”, “team” : “team-1”, “score” : 48 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “name” : “user-2”, “team” : “team-2”, “score” : 91 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “team” : “team-0”, “score” : 43 }
for (var i = 4; i < 6; i++) {
  db.users.insert({
    name : "user-" + i,
    team : "team-" + (i % 3)
    });
}
결과 4건은 score가 있고 2건은 score가 없다.
{ “_id” : ObjectId(“537ac2fc3cba50cc281a7e94”), “name” : “user-0”, “team” : “team-0”, “score” : 51 }
{ “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “name” : “user-1”, “team” : “team-1”, “score” : 48 }
{ “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “name” : “user-2”, “team” : “team-2”, “score” : 91 }
{ “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “team” : “team-0”, “score” : 43 }
{ “_id” : ObjectId(“537ac37f3cba50cc281a7e98”), “name” : “user-4”, “team” : “team-1” }
{ “_id” : ObjectId(“537ac37f3cba50cc281a7e99”), “name” : “user-5”, “team” : “team-2” }

find() 에 조건을 넣어보자.

  • db.users.find(); 전체를 출력한다.
  • db.users.find({key:value}); key와 value에 해당하는 값이 출력된다.

ex)

  • name이 user-1인것을 출력
    db.users.find({name: “user-1”});
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “name” : “user-1”, “team” : “team-1”, “score” : 48 }
  • 정규표현식을 사용해서 user-1~3을 출력
    db.users.find({name: /user-[1-3]/});
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “name” : “user-1”, “team” : “team-1”, “score” : 48 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “name” : “user-2”, “team” : “team-2”, “score” : 91 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “team” : “team-0”, “score” : 43 }
  • score가 30 이상인것을 출력.
    • $gt $gte
    • $lt $lte
    • $ne
      db.users.find({score: {$gt:30} });
      { “_id” : ObjectId(“537ac2fc3cba50cc281a7e94”), “name” : “user-0”, “team” : “team-0”, “score” : 51 }
      { “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “name” : “user-1”, “team” : “team-1”, “score” : 48 }
      { “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “name” : “user-2”, “team” : “team-2”, “score” : 91 }
      { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “team” : “team-0”, “score” : 43 }
  • user-1이 아닌것을 출력
    db.users.find({name : { $ne: “user-1”} } );
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e94”), “name” : “user-0”, “team” : “team-0”, “score” : 51 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “name” : “user-2”, “team” : “team-2”, “score” : 91 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “team” : “team-0”, “score” : 43 }
    { “_id” : ObjectId(“537ac37f3cba50cc281a7e98”), “name” : “user-4”, “team” : “team-1” }
    { “_id” : ObjectId(“537ac37f3cba50cc281a7e99”), “name” : “user-5”, “team” : “team-2” }

$and, $or, distinct 를 사용해 보자.

  • AND
    db.users.find({
    team: "team-0",
    score: { $lt: 50}
    });
    
    … … … { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “team” : “team-0”, “score” : 43 }
db.users.find({
  $and : [
    { team: "team-0" } ,
    { score: { $lt: 50} }
    ]
});
… … … … … { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “team” : “team-0”, “score” : 43 }
  • $OR
    • $in : [ xxx , xxx ] 가 배열에 있는지 검사한다.
    • $exists: 있는 것에만 검사한다.
      db.users.find({
      $or : [
      { team: { $in: ["team-0", "team-1"] } } ,
      { score: { $exists : true } }
      ]
      });
      
      … … … … …
      { “_id” : ObjectId(“537ac2fc3cba50cc281a7e94”), “name” : “user-0”, “team” : “team-0”, “score” : 51 }
      { “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “name” : “user-1”, “team” : “team-1”, “score” : 48 }
      { “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “name” : “user-2”, “team” : “team-2”, “score” : 91 }
      { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “team” : “team-0”, “score” : 43 }
      { “_id” : ObjectId(“537ac37f3cba50cc281a7e98”), “name” : “user-4”, “team” : “team-1” }
  • distinct
    • 어떤 종류가 있는지 검사
      db.users.distinct(‘team’);
      [ “team-0”, “team-1”, “team-2” ]

추출 데이터 결과를 가공해 보자.

  • db.users.find({}) 을 가공해보자.
  • find( {}, 조건식); 을 사용한다.
  • name만 선택하면
    db.users.find({},{name:1});
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e94”), “name” : “user-0” }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “name” : “user-1” }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “name” : “user-2” }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3” }
    { “_id” : ObjectId(“537ac37f3cba50cc281a7e98”), “name” : “user-4” }
    { “_id” : ObjectId(“537ac37f3cba50cc281a7e99”), “name” : “user-5” }
  • name만 선택하지 않으려면
    db.users.find({},{name:0});
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e94”), “team” : “team-0”, “score” : 51 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “team” : “team-1”, “score” : 48 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “team” : “team-2”, “score” : 91 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “team” : “team-0”, “score” : 43 }
    { “_id” : ObjectId(“537ac37f3cba50cc281a7e98”), “team” : “team-1” }
    { “_id” : ObjectId(“537ac37f3cba50cc281a7e99”), “team” : “team-2” }
  • name과 score만 출력해 보자.
    db.users.find({}, {name:1, score:1});
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e94”), “name” : “user-0”, “score” : 51 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e95”), “name” : “user-1”, “score” : 48 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e96”), “name” : “user-2”, “score” : 91 }
    { “_id” : ObjectId(“537ac2fc3cba50cc281a7e97”), “name” : “user-3”, “score” : 43 }
    { “_id” : ObjectId(“537ac37f3cba50cc281a7e98”), “name” : “user-4” }
    { “_id” : ObjectId(“537ac37f3cba50cc281a7e99”), “name” : “user-5” }
  • 두가지를 mix할때 제외가 되면 에러가 발생한다.
    db.users.find( {}, {name:1, score:0});
    error: {
    “$err” : “Can’t canonicalize query: BadValue Projection cannot have a mix of inclusion and exclusion.”,
    “code” : 17287
    }
  • 혼용 mix해서 사용하는 것은 _id만 가능하다는 점에 주의할 것.
    db.users.find( {}, {name:1, score:1, _id:0});
    { “name” : “user-0”, “score” : 51 }
    { “name” : “user-1”, “score” : 48 }
    { “name” : “user-2”, “score” : 91 }
    { “name” : “user-3”, “score” : 43 }
    { “name” : “user-4” }
    { “name” : “user-5” }
  • findOne () 출력 수를 제한해 보자.
    db.users.findOne({}, {_id:0});
    { “name” : “user-0”, “team” : “team-0”, “score” : 51 }
  • limit(3) 출력수를 3개로 제한해 보자.
    db.users.find( {}, {_id:0}).limit(3);
    { “name” : “user-0”, “team” : “team-0”, “score” : 51 }
    { “name” : “user-1”, “team” : “team-1”, “score” : 48 }
    { “name” : “user-2”, “team” : “team-2”, “score” : 91 }
  • skip(2) 마지막 2개를 건너 뛰어 보자.
    db.users.find( {}, {_id:0}).skip(2).limit(3);
    { “name” : “user-2”, “team” : “team-2”, “score” : 91 }
    { “name” : “user-3”, “team” : “team-0”, “score” : 43 }
    { “name” : “user-4”, “team” : “team-1” }
  • sort(score:1) 정령해 보자. (1 오름차순, -1 내림차순)
    db.users.find( {}, {_id:0}).sort( {score:-1});
    { “name” : “user-2”, “team” : “team-2”, “score” : 91 }
    { “name” : “user-0”, “team” : “team-0”, “score” : 51 }
    { “name” : “user-1”, “team” : “team-1”, “score” : 48 }
    { “name” : “user-3”, “team” : “team-0”, “score” : 43 }
    { “name” : “user-4”, “team” : “team-1” }
    { “name” : “user-5”, “team” : “team-2” }
db.users.find( {}, {_id:0}).sort({score:1});
{ “name” : “user-4”, “team” : “team-1” }
{ “name” : “user-5”, “team” : “team-2” }
{ “name” : “user-3”, “team” : “team-0”, “score” : 43 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 48 }
{ “name” : “user-0”, “team” : “team-0”, “score” : 51 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 91 }

색인(index)를 사용해 보자.

  • 키를 사용하면 검색 속도를 빠르게 만든다.
  • db.COL.getIndexes(); 인덱스 출력
    db.users.getIndexes()
    [
    {
       "v" : 1,
       "key" : {
           "_id" : 1
       },
       "name" : "_id_",
       "ns" : "mydb.users"
    
    }
    ]
  • db.COL.ensureIndex(); score를 오름차순으로 하는 인덱스 추가
    db.users.ensureIndex({score:1});
    {
    “createdCollectionAutomatically” : false,
    “numIndexesBefore” : 1,
    “numIndexesAfter” : 2,
    “ok” : 1
    }
  • 맞게 색인이 되었는지 확인해 보자.
    db.users.getIndexes();
    [
    {
       "v" : 1,
       "key" : {
           "_id" : 1
       },
       "name" : "_id_",
       "ns" : "mydb.users"
    
    },
    {
       "v" : 1,
       "key" : {
           "score" : 1
       },
       "name" : "score_1",
       "ns" : "mydb.users"
    
    }
    ]
  • unique key를 설정해 보자.
    db.users.ensureIndex( {name:1}, {unique:true});
    {
    “createdCollectionAutomatically” : false,
    “numIndexesBefore” : 1,
    “numIndexesAfter” : 2,
    “ok” : 1
    }
  • 유일한 값에 추가로 값을 넣으려 하면 에러가 발생한다.
    db.users.insert( {name:”user-0”});
    WriteResult({
    “nInserted” : 0,
    “writeError” : {
       "code" : 11000,
       "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$name_1  dup key: { : \"user-0\" }"
    
    }
    })
  • db.COL.dropIndex(); 인덱스 삭제
    db.users.dropIndex( {score:1});
    { “nIndexesWas” : 2, “ok” : 1 }

update 갱신을 해보자.

  • update를 사용해서 쓰면 될것이라고 생각하지만 score 만 들어간다.
  • 즉 이것은 스키마레스이기 때문에 발생하는 현상이다. 주의하자.
db.users.update( {name:”user-0”}, {score:100});
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find({}, {_id:0});
{ “score” : 100 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 48 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 91 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 43 }
{ “name” : “user-4”, “team” : “team-1” }
{ “name” : “user-5”, “team” : “team-2” }
  • user-0에 score만 바꿔 주려면 $set을 사용하면 된다.
db.users.update( {name:”user-1”}, {$set: {score:100}});
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find( {}, {_id:0});
{ “score” : 100 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 100 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 91 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 43 }
{ “name” : “user-4”, “team” : “team-1” }
{ “name” : “user-5”, “team” : “team-2” }
  • $unset 지울때 사용하는데 이때 “”하는 것에 주의하자.
db.users.update( {name:”user-1”},{$unset:{score:””}});
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find( {}, {_id:0});
{ “score” : 100 }
{ “name” : “user-1”, “team” : “team-1” }
{ “name” : “user-2”, “team” : “team-2”, “score” : 91 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 43 }
{ “name” : “user-4”, “team” : “team-1” }
{ “name” : “user-5”, “team” : “team-2” }
  • $inc 값을 줄이거나 늘려준다.
db.users.update( {name:”user-2”}, {$inc: {score:-10}});
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find( {}, {_id:0});
{ “score” : 100 }
{ “name” : “user-1”, “team” : “team-1” }
{ “name” : “user-2”, “team” : “team-2”, “score” : 81 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 43 }
{ “name” : “user-4”, “team” : “team-1” }
{ “name” : “user-5”, “team” : “team-2” }
  • $rename 이름을 바꿀때 사용한다.
db.users.update({name:”user-2”}, {$rename:{score:”myscore”}});
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find( {}, {_id:0});
{ “score” : 100 }
{ “name” : “user-1”, “team” : “team-1” }
{ “name” : “user-2”, “team” : “team-2”, “myscore” : 81 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 43 }
{ “name” : “user-4”, “team” : “team-1” }
{ “name” : “user-5”, “team” : “team-2” }

multi 를 사용해 보자.

  • update 하면 한개만 증가하므로 주의하자. 이때 사용하는 것이 multi이다.
    db.users.find ({},{_id:0});
    { “name” : “user-0”, “team” : “team-0”, “score” : 87 }
    { “name” : “user-1”, “team” : “team-1”, “score” : 6 }
    { “name” : “user-2”, “team” : “team-2”, “score” : 10 }
    { “name” : “user-3”, “team” : “team-0”, “score” : 91 }
    { “name” : “user-4”, “team” : “team-1”, “score” : 37 }
    { “name” : “user-5”, “team” : “team-2”, “score” : 3 }
db.users.update( {team:”team-0”},{$inc:{score:10}});
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find( {},{_id:0});
{ “name” : “user-0”, “team” : “team-0”, “score” : 97 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 6 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 10 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 91 }
{ “name” : “user-4”, “team” : “team-1”, “score” : 37 }
{ “name” : “user-5”, “team” : “team-2”, “score” : 3 }
  • team-0에 해당하는 모든 것을 10식 증가하려면 multi를 사용한다.
db.users.update( {team:”team-0”}, {$inc:{score:10}},{multi:true});
WriteResult({ “nMatched” : 2, “nUpserted” : 0, “nModified” : 2 })
db.users.find( {}, {_id:0});
{ “name” : “user-0”, “team” : “team-0”, “score” : 107 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 6 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 10 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 101 }
{ “name” : “user-4”, “team” : “team-1”, “score” : 37 }
{ “name” : “user-5”, “team” : “team-2”, “score” : 3 }

upsert, remove

  • upsert : (update / insert)
db.users.update({name:”hephaex”}, {name:”hephaex”, team:”team-0”,score:100});
WriteResult({ “nMatched” : 0, “nUpserted” : 0, “nModified” : 0 })
db.users.find( {}, {_id:0});
{ “name” : “user-0”, “team” : “team-0”, “score” : 107 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 6 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 10 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 101 }
{ “name” : “user-4”, “team” : “team-1”, “score” : 37 }
{ “name” : “user-5”, “team” : “team-2”, “score” : 3 }
  • name에 hephaex가 없기 때문에 자료는 변하되지 않았다.
  • 여기서 upsert:true를 추가하면 update와 동시에 insert를 한다.
db.users.update({name:”hephaex”}, {name:”hephaex”, team:”team-0”,score:100},{upsert:true});
WriteResult({
“nMatched” : 0,
“nUpserted” : 1,
“nModified” : 0,
“_id” : ObjectId(“537b07559b3de117452cd708”)
})
확인해 보자
db.users.find( {}, {_id:0});
{ “name” : “user-0”, “team” : “team-0”, “score” : 107 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 6 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 10 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 101 }
{ “name” : “user-4”, “team” : “team-1”, “score” : 37 }
{ “name” : “user-5”, “team” : “team-2”, “score” : 3 }
{ “name” : “hephaex”, “team” : “team-0”, “score” : 100 }
  • remove 에 조건에 맞는 것만 지우기
db.users.remove( {name:”hephaex”});
WriteResult({ “nRemoved” : 1 })
db.users.find( {}, {_id:0});
{ “name” : “user-0”, “team” : “team-0”, “score” : 107 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 6 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 10 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 101 }
{ “name” : “user-4”, “team” : “team-1”, “score” : 37 }
{ “name” : “user-5”, “team” : “team-2”, “score” : 3 }

mongodump, mongorestore를 해보자.

  • 백업과 복원과정이다.
mongodump -d mydb
connected to: 127.0.0.1
2011-05-20T16:48:26.768+0900 DATABASE: mydb to dump/mydb
2011-05-20T16:48:26.769+0900 mydb.system.indexes to dump/mydb/system.indexes.bson
2011-05-20T16:48:26.770+0900 1 documents
2011-05-20T16:48:26.770+0900 mydb.users to dump/mydb/users.bson
2011-05-20T16:48:26.771+0900 6 documents
2011-05-20T16:48:26.771+0900 Metadata for mydb.users to dump/mydb/users.metadata.json
  • 폴더에서 확인해 보면 dump가 생겼다.
ls
dump
  • 그럼 복원을 해보자.
  • 우선 자료를 변형 시키자. (team-0를 모두 지우자.)
db.users.remove({team:”team-0”});
WriteResult({ “nRemoved” : 2 })
db.users.find( {},{_id:0});
{ “name” : “user-1”, “team” : “team-1”, “score” : 6 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 10 }
{ “name” : “user-4”, “team” : “team-1”, “score” : 37 }
{ “name” : “user-5”, “team” : “team-2”, “score” : 3 }
  • 복원해보자.
mongorestore —drop
connected to: 127.0.0.1
2011-05-20T16:54:27.841+0900 dump/mydb/users.bson
2011-05-20T16:54:27.841+0900 going into namespace [mydb.users]
2011-05-20T16:54:27.841+0900 dropping
6 objects found
2011-05-20T16:54:27.844+0900 Creating index: { key: { id: 1 }, name: “_id“, ns: “mydb.users” }
mongo mydb
MongoDB shell version: 2.6.0
connecting to: mydb
db.users.find( {}, {_id:0});
{ “name” : “user-0”, “team” : “team-0”, “score” : 107 }
{ “name” : “user-1”, “team” : “team-1”, “score” : 6 }
{ “name” : “user-2”, “team” : “team-2”, “score” : 10 }
{ “name” : “user-3”, “team” : “team-0”, “score” : 101 }
{ “name” : “user-4”, “team” : “team-1”, “score” : 37 }
{ “name” : “user-5”, “team” : “team-2”, “score” : 3 }
  • 복원된 것을 확인할 수 있다.