몽고디비설치를 하고 사용해보자. 설치전 몽고의 기본 개념을 읽고 시작하자
* MongoDB는 웹 애플리케이션과 인터넷 기반을 위해 설계된 데이터베이스 관리 시스템이다. 데이터 모델과 지속성 전략은 높은 읽기/쓰기 효율과 자동 장애조치(failover)를 통한 확장의 용이성을 염두에 두고 만들어졌다. 애플리케이션에서 필요한 데이터베이스 노드가 하나거나 혹은 그 이상이거나에 관계없이 MongoDB는 놀라울 정도로 좋은 성능을 보여준다. 관계 데이터베이스를 확장하는 데 어려움을 겪었던 적이 있다면 이것은 대단한 뉴스일 것이다.
1. 설치후 4개파일 별도 디렉토리에 copy
+ mongodb 폴더 안에 4개 파일 copy
+ mongo.exe : 쉘 / mongod.exe : 서버 / mongofiles.exe : gridFS 빅데이터 핸들링 / mongos.exe : 라우터 서버
[dowon@localhost mongodb]$ ls
bsondump mongodump mongooplog mongosniff THIRD-PARTY-NOTICES
GNU-AGPL-3.0 mongoexport mongoperf mongostat
mongo mongofiles mongorestore mongotop
mongod mongoimport mongos README
[dowon@localhost mongodb]$ pwd
/home/dowon/MongoDB/mongodb <- binary files 위치
[dowon@localhost mongodb]$ cd ..
[dowon@localhost MongoDB]$ pwd
/home/dowon/MongoDB
[dowon@localhost MongoDB]$ ls
db01 db02 db03 mongodb <- 디렉토리들
[dowon@localhost MongoDB]$
2. 별도 디렉토리 만들고 서버 시작
+ mDB01, mDB02, mDB03 디렉토리를 만듦 : Replica Set을 만들 것이다.
+ 서버 시작하기
[dowon@localhost mongodb]$ ./mongod --dbpath /home/dowon/MongoDB/db01 &
[1] 5840
[dowon@localhost mongodb]$ Fri Dec 28 19:39:42
Fri Dec 28 19:39:42 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Fri Dec 28 19:39:42
Fri Dec 28 19:39:42 [initandlisten] MongoDB starting : pid=5840 port=27017 dbpath=/home/dowon/MongoDB/db01 32-bit host=localhost.localdomain
Fri Dec 28 19:39:42 [initandlisten]
Fri Dec 28 19:39:42 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
Fri Dec 28 19:39:42 [initandlisten] ** see http://blog.mongodb.org/post/137788967/32-bit-limitations
Fri Dec 28 19:39:42 [initandlisten] ** with --journal, the limit is lower
Fri Dec 28 19:39:42 [initandlisten]
Fri Dec 28 19:39:42 [initandlisten] db version v2.2.2, pdfile version 4.5
Fri Dec 28 19:39:42 [initandlisten] git version: d1b43b61a5308c4ad0679d34b262c5af9d664267
Fri Dec 28 19:39:42 [initandlisten] build info: Linux domU-12-31-39-01-70-B4 2.6.21.7-2.fc8xen #1 SMP Fri Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION=1_49
Fri Dec 28 19:39:42 [initandlisten] options: { dbpath: "/home/dowon/MongoDB/db01" }
Fri Dec 28 19:39:42 [initandlisten] Unable to check for journal files due to: boost::filesystem::basic_directory_iterator constructor: No such file or directory: "/home/dowon/MongoDB/db01/journal"
Fri Dec 28 19:39:42 [websvr] admin web console waiting for connections on port 28017
Fri Dec 28 19:39:42 [initandlisten] waiting for connections on port 27017
3. 쉘사용하기 : JavaScript 코딩을 통하여 작업을 한다.
(명령뒤에 s 붙으면 목록이다, MongoDB는 자바스크립트 엔진인 extended Spidermonkey shell을 탑재함)
[dowon@localhost mongodb]$ ./mongo
MongoDB shell version: 2.2.2
connecting to: test
Fri Dec 28 19:45:29 [initandlisten] connection accepted from 127.0.0.1:44889 #2 (1 connection now open)
> 2+3
5
> 'hello dowon'
hello dowon
> var dowon = function() {
... return 'hi youngsik. what are you doing now?'
... }
> dowon()
hi youngsik. what are you doing now?
- {} : 자바스크립 객체이다. anonymous function이고 일반 find() 시퀀스에 "어나너머스 자바스크립트 객체" = 클로저(Closure) 하나를 집어 넣은 것이다.
> use peopleDB // 데이터베이스 만들기
switched to db peopleDB
> db // db 명이 peopleDB를 referencing 한다
peopleDB
> show dbs
local (empty)
test (empty)
> db.people.save({age:37, name:'dowon', sex:'male'}) // collection (table) 만들기. JavaScript객체-JSON
Fri Dec 28 19:53:25 [FileAllocator] allocating new datafile /home/dowon/MongoDB/db01/peopleDB.ns, filling with zeroes...
Fri Dec 28 19:53:25 [FileAllocator] creating directory /home/dowon/MongoDB/db01/_tmp
Fri Dec 28 19:53:25 [FileAllocator] done allocating datafile /home/dowon/MongoDB/db01/peopleDB.ns, size: 16MB, took 0.012 secs
Fri Dec 28 19:53:25 [FileAllocator] allocating new datafile /home/dowon/MongoDB/db01/peopleDB.0, filling with zeroes...
Fri Dec 28 19:53:25 [FileAllocator] done allocating datafile /home/dowon/MongoDB/db01/peopleDB.0, size: 16MB, took 0.002 secs
Fri Dec 28 19:53:25 [FileAllocator] allocating new datafile /home/dowon/MongoDB/db01/peopleDB.1, filling with zeroes...
Fri Dec 28 19:53:25 [FileAllocator] done allocating datafile /home/dowon/MongoDB/db01/peopleDB.1, size: 32MB, took 0.001 secs
Fri Dec 28 19:53:25 [conn2] build index peopleDB.people { _id: 1 }
Fri Dec 28 19:53:25 [conn2] build index done. scanned 0 total records. 0 secs
Fri Dec 28 19:53:25 [conn2] insert peopleDB.people keyUpdates:0 locks(micros) w:201336 200ms
> show dbs // collection을 만들때 즉, save 할때 데이터베이스가 생성된다
local (empty)
peopleDB 0.0625GB
test (empty)
> show collections // collections (테이블)보기
people
system.indexes
> db.people.find()
{ "_id" : ObjectId("50de69359db888890e4126da"), "age" : 37, "name" : "dowon", "sex" : "male" }
> var person=[age:22]
Fri Dec 28 19:55:55 SyntaxError: missing ] after element list (shell):1
> var person={age:22};
> db.people.save(person) // 변수로 차기도 가능
> db.people.find()
{ "_id" : ObjectId("50de69359db888890e4126da"), "age" : 37, "name" : "dowon", "sex" : "male" }
{ "_id" : ObjectId("50de6a0e9db888890e4126db"), "age" : 22 }
> db.people.find({age:22})
{ "_id" : ObjectId("50de6a0e9db888890e4126db"), "age" : 22 }
>
- index 넣고 확인하기
1 : ascending
0 : descending
> db.people.ensureIndex({age:1});
Fri Dec 28 20:17:20 [conn2] build index peopleDB.people { age: 1.0 }
Fri Dec 28 20:17:20 [conn2] build index done. scanned 2 total records. 0.002 secs
> db.people.ensureIndex({name:0});
Fri Dec 28 20:17:26 [conn2] build index peopleDB.people { name: 0.0 }
Fri Dec 28 20:17:26 [conn2] build index done. scanned 2 total records. 0.002 secs
> db.people.getIndexes();
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "peopleDB.people",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"age" : 1
},
"ns" : "peopleDB.people",
"name" : "age_1"
},
{
"v" : 1,
"key" : {
"name" : 0
},
"ns" : "peopleDB.people",
"name" : "name_0"
}
]
- help 명령 보기 : 펑션이 이미 정의되어 있다
> db.people.help()
DBCollection help
db.people.find().help() - show DBCursor help
db.people.count()
db.people.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
db.people.convertToCapped(maxBytes) - calls {convertToCapped:'people', size:maxBytes}} command
db.people.dataSize()
db.people.distinct( key ) - e.g. db.people.distinct( 'x' )
db.people.drop() drop the collection
db.people.dropIndex(index) - e.g. db.people.dropIndex( "indexName" ) or db.people.dropIndex( { "indexKey" : 1 } )
db.people.dropIndexes()
db.people.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
db.people.reIndex()
db.people.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
e.g. db.people.find( {x:77} , {name:1, x:1} )
db.people.find(...).count()
db.people.find(...).limit(n)
db.people.find(...).skip(n)
db.people.find(...).sort(...)
db.people.findOne([query])
db.people.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
db.people.getDB() get DB object associated with collection
db.people.getIndexes()
db.people.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
db.people.insert(obj)
db.people.mapReduce( mapFunction , reduceFunction , <optional params> )
db.people.remove(query)
db.people.renameCollection( newName , <dropTarget> ) renames the collection.
db.people.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
db.people.save(obj)
db.people.stats()
db.people.storageSize() - includes free space allocated to this collection
db.people.totalIndexSize() - size in bytes of all the indexes
db.people.totalSize() - storage allocated for all data and indexes
db.people.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi
db.people.validate( <full> ) - SLOW
db.people.getShardVersion() - only for use with sharding
db.people.getShardDistribution() - prints statistics about data distribution in the cluster
db.people.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
'MongoDB > Concept' 카테고리의 다른 글
[MongoDB] 왜 나오게 된것일까 (0) | 2013.10.10 |
---|---|
[MongoDB] 설치후 사용하기 (2) (0) | 2013.07.20 |
[MongoDB] 데이터 수집과 동시에 레포팅을 생성할 때 (0) | 2013.01.24 |
[MongoDB] 기본 개념, Replica/Shard (0) | 2012.12.29 |