/*select count(*) from employees*/
>db.employees.aggregate([{$group:{_id:null, count:{$sum:1}}}])

/*select sum(sal) from employees*/
>db.employees.aggregate([{$group:{_id:"$deptno",total:{$sum:"$sal"}}}])

/*select deptno,sum(sal) from employees where sal=3000 group by deptno*/
>db.employees.aggregate([{$match:{sal:3000}}, {$group:{_id:"deptno", total:{$sum:"$sal"}}}])

/*deptno가 10인 데이터를 조회*/
>db.employees.find({deptno:{$all:[10]}},{_id:0, empno:1,ename:1,sal:1})

/*deptno가 10이고 deptno가 30인 데이터를 조회*/
>db.employees.find({deptno:{$all:[10,30]}},{_id:0, empno:1,ename:1,sal:1})

>db.employees.find({$and:[{deptno:10},{deptno:30}]},{_id:0, empno:1,ename:1,sal:1})

/*deptno가 10이거나 deptno가 30인 데이터를 조회*/
>db.employees.find({deptno:{$in:[10,30]}},{_id:0, empno:1,ename:1,sal:1})

>db.employees.find({$or:[{deptno:30},{deptno:10}]},{_id:0, empno:1,ename:1,sal:1})

/*comm field가 존재하는 데이터만 조회하라*/
db.employees.find({comm:{$exists:true}},{_id:0,empno:1,ename:1})

'mongoDB' 카테고리의 다른 글

mongoDB select문  (0) 2013.03.11
mongoDB 명령어  (1) 2013.03.08
by pacino.kang 2013. 3. 13. 13:31

1.emp collection 생성
>for (var i=1; i<=20; i++) db.emp.save({empno:i, empname:"test", sal:100})
>db.emp.find()

2.배열에 결과저장 배열에 저장되어 있는 내용출력
>var cur = db.emp.find()
>while(cur.hasNext()) printjson(cur.next())

3.배열의 특정 순번에 있는 내용출력
>var cur = db.emp.find()
>printjson(cur[10])

4.Date함수를 통해 현재 날짜 출력
>x=new Date()

5.x변수에 저장된 날짜를 문자열로 출력
>x.toString()

6.ISODate 함수를 통해 현재 날짜를 출력
>d=ISODate()
>d.getMonth()
>d.getYear()
>d.getDay()

7.Sequence Number 함수
>Function seq_no("name"){
  var ret=db.seq_no.findAndModify(query:{_id:name},
                                             update:{$inc:{next:1}},
                                             "new"true, upsert:true});
  return ret.next;
  }
원리는 seq_no라는 함수형 collection을 만들어서 해당 _id 별로
+1씩 증가시킨 값을 리턴한다.

8.selec 문
/*select * from employees where empno=7369 */
>db.employees.find({empno:7369}).forEach(printjson)

/*select ename from employees where empno=7900*/
첫번째 인자 {empno:7900}은 where절이다.
두번째 인자 {ename:""}은 select 절이다.
>db.employees.find({empno:7900}, {ename:""}).forEach(printjson)

/*select ename,job from employees where empno=7900*/
>db.employees.find({empno:7900}, {ename:"", job:""}).forEach(printjson)

9.index 생성문과 select  문
>db.employees.ensureIndex({ename:1})
/*select empno, ename from employees where ename>='ALLEN' and ename<= 'SCOTT';*/
>db.employees.find({}, {_id:0, empno:1, ename:1}).min({ename:"ALLEN"}).max({ename:"SCOTT"})

/*SELECT EMPNO, ENAME, HIREDATE FROM EMPLOYEES WHERE DEPTNO>=20 AND DEPTNO<=30*/
>db.employees.ensureIndex({deptno:1})
>db.employees.find({$min : {deptno:20}, $max: {deptno:30}, $query:{}}, {_id:0,empno:1,ename:1,hiredate:1})

/*select empno, ename from employees where empno>7500 and empno<=7600*/
>db.employees.find({empno:{$gt:7500, $lte:7600}},{_id=0,empno:1,ename:1})

/*select empno, ename, from employees where empno=7782 or empno=7844*/
>db.employees.find({$or:[{empno:7782}, {empno:7844}]},{_id=0, empno:1, ename:1})

/*select count(*) from employees:*/
>db.employees.count()

/*select count(*) from employees where empno>7900*/
>db.employees.find({empno:{$gt:7900}}).count()

/*select distinct deptno from employees;*/
>db.employees.distinct("deptno");

/*select deptno, sum(sal) csum
    from employees
  where hiredate>="01-01-1980" and hiredate <= "31-12-1981"
  group by deptno*/
>db.employees.group({key: {deptno:true},
                            cond: {"hiredate": {$gte: "01-01-1980", $lt:"31-12-1981"}},
                            reduce: function(obj,prev) {prev.csum += obj.sal;},
                            initial:{csum:0}
  })

/*select ename, job from employees where deptno=10 order by ename desc*/
db.employees.find({deptno:10},{_id:0,ename:1,job:1}).sort(ename:-1)

'mongoDB' 카테고리의 다른 글

mongoDB 2.1.2 이상에서 제공되는 함수  (0) 2013.03.13
mongoDB 명령어  (1) 2013.03.08
by pacino.kang 2013. 3. 11. 17:45

1. 데이터베이스가 생성될 물리적 경로생성
c:\>mkdir c:\MONGODB\test

2. mongoDB 버전 확인
>mongod --version

3. mongoDB 인스턴스 활성화
>mongod --dbpath c:\mongodb\test
-- mogodb shell프로그램 실행
>mongo

4.test 데이터베이스로 이동할때
>use test

5. 데이터베이스 목록 출력
>show dbs

6. 데이터베이스 상태확인
>db.stats()

7. 데이터베이스 shutdown
admin 영억으로 이동후에 셧다운 해야함.
>use admin 
>db.shutdownServer()

8. 데이터베이스 로그아웃
>db.logout()

9.collection 생성
capped:true이면 해당 익스텐트를 모두 사용하게되면
처음부터 재 사용할 수 있는 데이터 구조를 생성할 때
size 해당 Collection의 최초 생성크기
>db.createCollection("emp",{capped:false, size:8192});

10. colection list보기
show collections

11. collection의 현재상태 및 정보분석
>db.emp.validate();

12.collection의 이름변경
>db.emp.renameCollection("employee")

13.Collection의 삭제
>db.employee.drop();

14.collection에 데이터 INSERT
>db.emp.insert({eno:1101,fname:"JIMMY"});

15.collection에 데이터 UPDATE
>db.emp.update({eno:1101},{$set:{fname:"JOO"}});

16.collection에 데이터 SELECT
>db.emp.find().sort({eno:-1});

17.도큐먼트(row)부터 정의하고 collection 생성
>m={ename :  "smith"}
>n={ename :  1101}
>db.things.save(m)
>db.things.save(n)
>db.things.find()
>db.things.insert({ empno : 1102, ename:"king"})

18.for문을 이용한 증감된 값을 Collection에 insert
>for(var n=1103; n<=1120; n++) db.things.save({n:n, m:"test"+n})

19.db.things.find()로 조회시 리스트가 20 row가 넘는 경우 다음 페이지를 보고싶을때
>it


 

'mongoDB' 카테고리의 다른 글

mongoDB 2.1.2 이상에서 제공되는 함수  (0) 2013.03.13
mongoDB select문  (0) 2013.03.11
by pacino.kang 2013. 3. 8. 17:24

NOSQL이란?

No SQL
Not ONLY SQL
Non-Relational Operation Database SQL
RDBMS는 클라우드 컴퓨팅 환경에서 발생하는 빅데이터를 효과적으로
저장, 관리하는데 여러 가지 문제점이 발생하고 있는 상황에 직면
이런 문제점을 보완하기 위해 새로운 저장기술이 필요하게됨
이러한 배경에서 태어난것이 NoSQL

nosql의 장점 및 단점

하드웨어 확장에 제약이 없다.
저렴한 비용으로 분산 병렬처리가 가능하다.
메모리 mapping기능을 통해 읽고 쓰기가 빠르다.
비정행 데이터구조로 설계비용이 감소한다.
join인 없는 구조로 simple하고 성능이 빠르다.
기존의 하드웨어를 활용하여 구축할 수 있다.
RDBMS를 사용한 많은 시간이 흐르면서 성능/관리면에서 안정기에 접어들었다면
NOSQL 아직 성장하고 있는 기술이기에 문제점도 존재하는 것이 사실이다.
하지만 빅데이터를 처리할 수 있는 새로운 요구와 맞물려 빠른 속도로 성장 할 것으로 예측됨
RDBMS가 클라이언트/서버환경에 맞는 데이터 저장기술이라면
NOSQL은 클라우드 환경에 맞는 데이터 저장기술이다.
NoSQL이 RDBMS를 완전 대체하기보다는 상호 보완적인으로
발전할 것으로 예상됨.

NoSQL의 종류

대략 150 가지 이상의 제품이 존재함.
하지만 실제 사용자층을 확보하고 있고 꾸준한 기술지원과 관리를 지원하는제품은
대략 6가지 정도가 있다.
MongoDB, Casandra, HBASE, CouchDB, Redis

NoSQL 제품 유형
1.key-value Database (Riak, Voldemort)
2.Document Database (mongoDB, CouchDB)
3.Big Table Database (Hbase, Casandra)
4.Graph Database (Sones,AllegroGraph)

by pacino.kang 2013. 3. 8. 11:45
| 1 |