mongoDB

[mongodb install] how to use mongodb

고요한하늘... 2011. 3. 22. 18:43

NOSQL이 요즘 인기를 끌고 있다. 

여러가지 오픈소스들이 존재하는데 C++이라는 친근한 언어와 여러 벤치마크에서 가장 포퍼먼스가 좋다고 해서 mongodb를 선택하게 됐다.

사용시에는 바이너리 버전을 받아 사용하다 보니 c++이라는 메리트는 전혀 없었다.


 

MONGODB REVIEW

mongodb에 대한 자세한 내용은 아래 URL에서 보세요

mongodb url : http://www.mongodb.org/


download url : http://www.mongodb.org/dr/fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.0.tgz/download

linux build page : http://www.mongodb.org/display/DOCS/Building+for+Linux

 

Pckage Contents

---------------------------------------------------------------------------

  bin/mongod             :  MongoDB server( sharding server, replica server, config server )

  bin/mongo               :  MongoDB client ( for user )

---------------------------------------------------------------------------

  bin/mongodump        :  MongoDB dump tool - for backups, snapshots, etc..

  bin/mongorestore     :  MongoDB restore a dump

  bin/mongoexport       :  Export a single collection to test (json,csv)

  bin/mongofiles          : Utility for putting and getting files from MongoDB gridf

  bin/mongoimportjson  :  Import a json file into a collection

 

 

                                             SINGLE SERVER TEST

SQL 명령어와 같은 기능의 MONGODB 명령어 리스트

 * http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart


MONGODB SERVER 구동

* ] mongod --dbpath=/data2/jchern/db [ --port 99999 ]

* 디렉토리를 만들고 해당 디렉토리를 파라미터로 넣는다. 포트를 지정해도 되지만 테스트를 위해서 default port를 사용하는 것이 좋다.


MONGODB CLIENT 구동

* ] mongo

* single 서버이기 때문에 mongo로만 실행이 된다.

실행후에

> show dbs

> use test

등 명령어를 입력


> db.coll.find()

> db.coll.save()

> db.coll.remove()

> db.coll.update()


 

                                                              MONGODB ( python ) 

python용 mongodb를 사용하기 위해 필요한 셋업툴

http://pypi.python.org/pypi?:action=show_md5&digest=7df2a529a074f613b509fb44feefe74e

tar -zxvf setuptools-0.6c11.tar.gz

su 

python setup.py install

cd setuptools-0.6c11/dist

sh setuptools-0.6c11-py2.7.egg


python용 mongodb : pymongo

url : http://pypi.python.org/pypi?:action=show_md5&digest=12e12163e6cc22993808900fb9629252

tar -zxvf pymongo-1.9.tar.gz 

 python setup.py install


 

                                                            PYTHON CODE 

#!/bin/python


import pymongo

connection = pymongo.Connection("ip", 27017)

db=connection.test

db.my_collection

db.my_collection.save({"x": 10})

db.my_collection.save({"x": 8})

db.my_collection.save({"x": 11})


db.my_collection.find_one()

for item in db.my_collection.find():

    print item["x"]

 

 

 

python용 mongodb 사용법

http://api.mongodb.org/python/1.9%2B/examples/custom_type.html#setup

 

 

                                   python test code

#!/usr/local/bin/python


import pymongo

connection = pymongo.Connection("ip", 27017)

db=connection['test']


#d1={'code': 'DAUM', 'keyword': 'mongo_db_test_keyword1'}

#db.test.insert(d1);

#d1={'code': 'NAVER', 'keyword': 'mongo_db_test_keyword2'}

#db.test.insert(d1);


list=[]

data={}

fp=open("sample.dat","r");

for line in fp:

    buf=line.rstrip('\n');

    fields=buf.split('\t')

    data['keyword'] = fields[0];

    data['code']    = fields[1];

    data['docid']   = fields[2];

    abc=data.copy();

    list.append(abc);

fp.close();

db.test.insert(list);


for rec in db.test.find({'code':'WOTO'}):

    print rec['keyword'];




                               input file format

 

다음        DAUM           1

네이버     NAVER          2

 


* 고급 기능

 url : http://www.mongodb.org/display/DOCSKR/Advanced+Queries


 

                         regular expression 

print "COND : WO*"

regex="^W.*";

for rec in db.test.find( { 'code' : re.compile(regex,re.IGNORECASE)}):

    print rec['code'], rec['keyword']


 

 

 

 

 

                                                                                 set up sharding sever                                                                


 

http://www.mongodb.org/display/DOCS/A+Sample+Configuration+Session

 


/data/db/a 디렉토리 생성


포트 10000번, 디렉토리 경로는 /data/db/a로 shard server 구동

] ./mongod --shardsvr --dbpath /data/db/a --port 10000 > /tmp/sharda.log &



/data/db/b 디렉토리 생성

포트 10001번, 디렉토리 경로는 /data/db/b로 shard server 구동

] ./mongod --shardsvr --dbpath /data/db/b --port 10001 > /tmp/shardb.log &



/data/db/config 디렉토리 생성

포트 20000번, 디렉토리 경로는 /data/db/config로 config server 구동

] ./mongod --configsvr --dbpath /data/db/config --port 20000 > /tmp/configdb.log &


config server의 포트와 동일한 ip,port로 mongos 구동

] ./mongos --configdb localhost:20000 > /tmp/mongos.log &


* mongos는 디렉토리 정보 없이 구동이 가능하다. 필요한 정보는 config server에서 가져온다

* config server와 configdb는 서로 다른 머신에서 구동시켜야 한다.



두개의 shard server를 추가하는 방법

 mongos를 설정한 서버에서 아래 명령어를 실행

> show dbs

> use admin


shard server 추가( 포트 10000번 추가 )

> db.runCommand( { addshard:"10.33.125.218:10000"})

{ "ok" : 1 }


shard server 추가( 포트 10001번 추가 )

> db.runCommand( { addshard:"10.33.125.218:10001"})

{ "ok" : 1 }


> db.runCommand( { enablesharding : "test" } )

{ "ok" : 1 }


> db.runCommand( { shardcollection : "test", key : { keyword : 1} } )

{ "ok" : 1 }



* tip : access denied 메세지가 보이면

> use admin으로 테스트하면 된다.

현재 설정된 db를 볼려면 커멘드 창에

> db를 입력



cf> 

shard server 서버로 등록된 것을 해제

> db.runCommand( { removeshard : "10.33.125.218:10000" } );


shard sever 상태보기

> db.printShardingStatus();

----------------------------------------------------

mongodb default port number

----------------------------------------------------

Standalone mongod : 27017

mongos : 27017

shard server (mongod --shardsvr) : 27018

config server (mongod --configsvr) : 27019

web stats page for mongod : add 1000 to port number (28017, by default)

 

 

* sharding server를 적용하기 위한 명령어( 이명령어를 실행하지 않으면 동일한 sharding server에 데이터가 저장된다 )
 > db.runCommand( { enablesharding : "test" } ); -> enablesharding : [DBNAME]
* index 만들기
 db.keyword.ensureIndex({"keyword":1})

 * sharding server를 구성한후 어떤 기준으로 데이터를 분산할지를 결정해야 하는데, 특정 필드를 index로 만들어 놓은후에 index로 만들어 놓은 필드중 하나를 분산용 필드로 지정해야 한다.

  > db.runCommand( { shardcollection : "test.keyword", key : { keyword : 1} } )

     ** 참고 http://www.mongodb.org/display/DOCS/Choosing+a+Shard+Key


sharding server list

>  use admin

> db.runCommand({listshards:1})


----------------------------------------------------

                   Append

----------------------------------------------------

Config Server
config 서버는 각각의 chunk와 shard 서버에 대한 기본적인 정보를 포함한 cluster의 meta 정보를 가지고 있다.
chunk 정보는 config server에 대한 주요 데이터이다.
각 config 서버는 모든 chunk에 대한 완전한 데이터를 가지고 있다.
two-phrase commit는 config 서버 가운데 설정 데이터의 일관성이 보장한다.
config 서버는 자신의 replication 모델을 사용한다. config서버는 replica set에서는 구동되지는 않는다.
만약에 config 서버가 다운되면 cluster의 메타 정보는 read only로 변경된다.
그러나 그런 상태일지라도 mongoDB cluseter는 여전히 기록된 내용을 읽을수는 있다.

Routing Processes
mongos 프로세스는 다양한 클러스터의 컴포넌트를 하나의 시스템에서 처리하는 것과 같이 협업 및 라운팅 기능을 한다고 할수 있다.
클라이언트로부터 request를 받으면 mongos 프로세스는 적당한 서버로 요청을 보내고 결과를 취합해 클라이언트로 보내는 역할을 한다.

mongos 프로세스는 영속적으로 동작하지는 않는다. 반면에 mongos는 구동시 config 서버에서 필요한 정보를 가져온다.
config server에 어떤 변화가 발생하면 그정보는 각각의 mongos 프로세스에 전파된다.

mongos 프로세스는 원하는 서버 어디에서는 구동할수 있다.
그들은 shard 서버 자체로 구동할수 있다. 각 application 서버에서 구동될만큼 충분히 가벼운 프로그램이다.
mongos 프로세스의 수는 제한이 없다.




 

                db functions

 

db.addUser(username, password[, readOnly=false])
db.auth(username, password)
db.cloneDatabase(fromhost)
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : ..., capped : ..., max : ... } )
db.currentOp() displays the current operation in the db
db.dropDatabase()
db.eval(func, args) run code server-side
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
db.getName()
db.getPrevError()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.printCollectionStats()
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus()
db.removeUser(username)
db.repairDatabase()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }
db.serverStatus()
db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.shutdownServer()
db.stats()
db.version() current version of the server
db.getMongo().setSlaveOk() allow queries on a replication slave server



           collections functions 

 

db.collname.find().help() - show DBCursor help
db.collname.count()
db.collname.dataSize()
db.collname.distinct( key ) - eg. db.collname.distinct( 'x' )
db.collname.drop() drop the collection
db.collname.dropIndex(name)
db.collname.dropIndexes()
db.collname.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
db.collname.reIndex()
db.collname.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
e.g. db.collname.find( {x:77} , {name:1, x:1} )
db.collname.find(...).count()
db.collname.find(...).limit(n)
db.collname.find(...).skip(n)
db.collname.find(...).sort(...)
db.collname.findOne([query])
db.collname.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
db.collname.getDB() get DB object associated with collection
db.collname.getIndexes()
db.collname.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
db.collname.mapReduce( mapFunction , reduceFunction , <optional params> )
db.collname.remove(query)
db.collname.renameCollection( newName , <dropTarget> ) renames the collection.
db.collname.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
db.collname.save(obj)
db.collname.stats()
db.collname.storageSize() - includes free space allocated to this collection
db.collname.totalIndexSize() - size in bytes of all the indexes
db.collname.totalSize() - storage allocated for all data and indexes
db.collname.update(query, object[, upsert_bool, multi_bool])
db.collname.validate() - SLOW
db.collname.getShardVersion() - only for use with sharding

 

----------------------------------------------------

   reference :

https://github.com/mongodb

http://exif.net/83

----------------------------------------------------


'mongoDB' 카테고리의 다른 글

mongodb test  (0) 2011.06.22
[mongodb mapreduce] time grouping  (0) 2011.06.01
[mongodb mapreduce] add integer value  (0) 2011.04.08
[mongodb mapreduce] string concatenate  (0) 2011.04.08
[mongodb] case study1  (0) 2011.03.22