'NoSQL'에 해당되는 글 5건

  1. 2015.11.17 :: mongdb sort, paging, plan
  2. 2015.11.17 :: mongodb crud(2)
  3. 2015.11.17 :: mongoDB crud(1)
  4. 2015.10.30 :: mongDB create table 및 색인 생성
  5. 2015.10.30 :: Mongo 단일 서버 설정
개발관련/MongoDB 2015. 11. 17. 11:51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//sort 
//asc     
db.crudtest.find(
    {
        
    }
    
).sort(
    {
        "name" : 1
    }
);      
    
//desc     
db.crudtest.find(
    {
        
    }
    
).sort(
    {
        "name" : -1
    }
);          
 
cs

sort는 sort라는 내부함수로 쓰며 1, -1로 오름 차순과 내림차순을 정한다. 


다음은 다량의 데이터를 넣는 bulk 또는 fetch 또는 batch 다. (용어는 =_=; 쓰기나름. )


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
db.users.insert(
    [
  {
    "_id""56497019adbf20c07138d982",
    "index"0,
    "isActive"false,
    "age"24,
    "eyeColor""blue",
    "name""Moon Robles",
    "gender""male",
    "company""MANTRIX",
    "email""moonrobles@mantrix.com"
  },
  {
    "_id""56497019be3cc168feb7b889",
    "index"1,
    "isActive"true,
    "age"32,
    "eyeColor""blue",
    "name""Annabelle Bass",
    "gender""female",
    "company""FOSSIEL",
    "email""annabellebass@fossiel.com"
  },
////////////////////생략/////////////////////////////////
{
    "_id""564970199f18e80dce7f2fed",
    "index"99,
    "isActive"false,
    "age"32,
    "eyeColor""brown",
    "name""Richardson Hansen",
    "gender""male",
    "company""AQUASURE",
    "email""richardsonhansen@aquasure.com"
  }
]
);
cs

insert문에 array형태로 넣으면 된다. 현재 robomongo tool에 의해 작업하므로 file load는 커널에서만 가능 하다. 


다음은 paging 기법.

1
2
3
/////////////////////paging//////////////////////////////
db.users.find().limit(10);
db.users.find().skip(10).limit(10);
cs

몇개의 결과를 가져올지에 대한 함수는 limit(count) 이며, 몇개를 skip할지에 대한 함수는 skip함수를 쓰면된다. 

다음은 색인 작업. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//////////////////////index//////////////////////////////////
db.users.ensureIndex( 
  {
      "index" : 1
  }
 ); 
db.users.ensureIndex( 
  {
      "email" : 1
  }
 ); 
//compound  
db.users.ensureIndex( 
  {
      "email" : 1,
      "index" : 1
  }
 );  
cs

복합(?) 인덱스의 경우 위의 예제처럼 사용 하면 된다. 

다음은 plan 또는 explain ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
///////////////////plan////////////////////////  
db.users.find(
  {
      "index":{
          $lte : 50
      }
  }
).explain();  
  
  
db.users.find(
  {
      $and :[
          {
          "index" : 
              { $lte :50
            }
           },
        {
            "name""Joseph Ferguson"
        },
        {
            "email" : "josephferguson@exiand.com"
        }
      ]
  }
).explain();    
cs
위 두개의 plan을 해본 쿼리 문이다. 이것의 결과는 상당히 만족 스럽게 나온다. (plan까지 지원하다니 ....) 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* 1 */
{
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "test2.users"//어느 db의 어느 collection 인지. 
        "indexFilterSet" : false
        "parsedQuery" : { //실행된 쿼리
            "index" : {
                "$lte" : 50.0000000000000000
            }
        },
        "winningPlan" : {
            "stage" : "FETCH",
            "inputStage" : { //index를 탔을때 쿼리가 실행되는 단계를 나타냄. 
                "stage" : "IXSCAN"//인덱스를 통해서 검색. 
                /**
                *
                COLLSCAN for a collection scan
                                IXSCAN for scanning index keys
                                FETCH for retrieving documents
                                SHARD_MERGE for merging results from shards
                */
                "keyPattern" : { 
                    "index" : 1.0000000000000000
                },
                "indexName" : "index_1",
                "isMultiKey" : false//compound 키 사용 여부. 
                "direction" : "forward",
                "indexBounds" : {
                    "index" : [ 
                        "[-inf.0, 50.0]"
                    ]
                }
            }
        },
        "rejectedPlans" : []//인텍스가 여러개일 경우 색인하지 않을 인덱스 값의 이름이 들어있다. 
    },
    "executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 51,//document 개수
        "executionTimeMillis" : 0,//실행 시간
        "totalKeysExamined" : 51//검색에 사용한 index를 통해서  개수. 
        "totalDocsExamined" : 51//collection에서 검색한 개수. 
        "executionStages" : { 
            "stage" : "FETCH",
            "nReturned" : 51// return 된 document 수. 
            "executionTimeMillisEstimate" : 0,
            "works" : 52
            "advanced" : 51
            "needTime" : 0,
            "needFetch" : 0,
            "saveState" : 0,
            "restoreState" : 0,
            "isEOF" : 1,
            "invalidates" : 0,
            "docsExamined" : 51,
            "alreadyHasObj" : 0,
            "inputStage" : {
                "stage" : "IXSCAN",
                "nReturned" : 51,
                "executionTimeMillisEstimate" : 0,
                "works" : 52,
                "advanced" : 51,
                "needTime" : 0,
                "needFetch" : 0,
                "saveState" : 0,
                "restoreState" : 0,
                "isEOF" : 1,
                "invalidates" : 0,
                "keyPattern" : {
                    "index" : 1.0000000000000000
                },
                "indexName" : "index_1",
                "isMultiKey" : false,
                "direction" : "forward",
                "indexBounds" : {
                    "index" : [ 
                        "[-inf.0, 50.0]"
                    ]
                },
                "keysExamined" : 51,
                "dupsTested" : 0,
                "dupsDropped" : 0,
                "seenInvalidated" : 0,
                "matchTested" : 0
            }
        },
        "allPlansExecution" : []
    },
    "serverInfo" : {
        "host" : "localhost",
        "port" : 35001,
        "version" : "3.0.4",
        "gitVersion" : "0481c958daeb2969800511e7475dc66986fa9ed5"
    }
}
cs


위 결과는 첫번째 예제를 실행 할때 나오는 결과 인데.. 중요한 key들이 몇개 보인다. 


state 경우 값이 COLLSCAN 인경우는 index를 타지 않았을 경우 값이 찍히고, 탔을 경우 IXSCAN 요런 값이 찍히게 된다. 


또 위 두번째 예제를 실행하면 rejectedPlans 에 key에 단일 색인 키들이 들어 갈것이다. 위 주석을 보고 참고 하면 된다. 





posted by 제스트
:
개발관련/MongoDB 2015. 11. 17. 11:12
1
2
db.crudtest.find();
 
cs

특정 collections의 데이터를 전체 가져올때 find()함수로 호출한다. 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
db.crudtest.find(
    {
        $and: [{
            "name":"hwang"
        },{
            
             "id":"wargen"
        }]
    }
 );
 
db.crudtest.find(
    {
        $or: [{
            "id":"wargen"
        },{
            
            "idx":2
        }]
    }
 )    
cs

 

and, or 검색은 위와 같이 $and, $or 의 명령어로 array 를 선언후 object 형태로 찾고자 하는 field를 선언한다. 


특정 배열의 값을 찾고자 할때는 다음과 같이 선언한다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
db.crudtest.find(
    {
        "language.0""java"
    }
);
    
db.crudtest.find(
    {
        "language" : {
            $all : ["js","java"]
            }
    }
 )     
cs


$all의 경우 array의 값이 있는 것들을 전체 다 찾아준다. 


다음은 mongodb의 꽃(?)이라 할수있는 변수 저장 이다. 

1
2
3
4
5
6
7
8
9
10
11
12
var temp = db.crudtest.find(
    {
       "type": {
           $ne : null
       }
    },
    {
        "type":1
    }
 );      
temp;
 
cs
위의 예제는 type이라는 필드에 값이 널이 아니고 type 필드에 값이 있는 document를 찾는 예제이다. 그런데 저 쿼리(?)를 temp라는 변수에 저장 후 temp;를 실행하면 결과가 화면에 나올것이다. 


이때 다시한번 temp; 를 하면 값이 나오지 않을 것이다. 이를 커서라 한다. 커서에 저장된 값 리턴될 값을 저장하는것이 아니고 실행될  쿼리를 저장한다. 그러므로 변수를 호출하면 쿼리가 호출되므로 커서의 값은 사라진다.


위의 예제의 값을 저장하고 싶다면 다음과 같이 생성해야한다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
 
var returnVal = function (){
    while(temp.hasNext()){
    var currentData = temp.next();
        for(var key in currentData.type){
            print(key);
        }
    }
};
 
    
    
returnVal();    
cs

js랑 똑같다. =_=; 



mongodb도 <, >, <=, >= 이런것들을 지원을 한다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
db.crudtest.find(
    {
        "idx" : {
            $lt : 2
        }
    }
);
    
db.crudtest.find(
    {
        "idx" : {
            $lte : 2
        }
    }
);    
    
db.crudtest.find(
    {
        "idx" : {
            $gte : 2
        }
    }
);        
 
db.crudtest.find(
    {
        "idx" : {
            $gt : 2
        }
    }
);        
cs


이상 find는 끝....

posted by 제스트
:
개발관련/MongoDB 2015. 11. 17. 10:50

1
2
3
4
5
6
7
8
9
10
11
12
13
use test
db.crudtest.insert(
    {
        "idx" : 1,
        "name" : "aaa",
        "id" : "aaa",
        "type" : {
            "test1" :"test1",
            "test2" :"test2"
        }
        
    }
);
cs


몽고 db는 내부에 js로 동작(?)하는 듯한 느낌이다. 


먼저 rdb 처럼 어떤 db를 사용할지를 선택한다.  rdb처럼 먼저 스키마를 생성하고 이런짓은 안하고 없으면 만들고 있으면 그냥 가져다 쓴다. 머 여타 nosql도 마찬가지지만. 


use test를 하면 (여기서 ; 세미콜론을 붙으면 안되더라구요 =_=;) db라는 객체에 저장이 되는듯하다. 

이후 db.(콜렉션이름).insert 후 저장할 값을 json형태로 저장하면 된다. 


콜렉션은 document 기반의 table을 뜻한다. 머 elasticsearch나 solr, lucene등 document기반이다. 


insert형식은 자유롭다. object 를 기본으로 하며, 각 키값(field) : value 여기서 value는 다시 object또는 array가 올수 있다. 


1
2
3
4
5
6
7
8
9
db.crudtest.insert(
    {
        "idx" : 3,
        "name" : "gno",
        "id" : "gno"
        
    }
)    
 
cs



다음은 update문이다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//update
db.crudtest.update(
    //where
    {
        "name" :"ryu"
    },
    
    {
        //set 
        $set:{"name":"gun-ho"}
        ,
        //add
        $set: {
            "language": ["java","js","angular"]
        },
        //field delete
        $unset : {
            "id" : 1
        }
    }
)
 
cs

update는 크게 두개의 object가 존재하며, 첫번째는 where절을 뜻한다. 두번째는 rdb로 보면 set의 개념을 저장한다. 
만약 필드의 값을 바꾸고 싶고 또는 추가 하고 싶다면  $set을 하면된다. 또, 특정 필드를 삭제하고 싶다면 $unset을 하면 된다. RDB와는 다르게 모든 Field(column)이 동일하지 않아도 된다. 

또, 위에 예제를 보면 language라는 필드에 array 값을 추가 하였다. 이때 값을 또 추가 싶다면 그때는 $push라는 명령어를 쓰면된다. 느낌이 jquery또는 js 내장 함수와 매우 흡사하다. 여러개의 값을 push해서 하고 싶다면 $eash라는 명령어를 사용하면 된다. 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
db.crudtest.update(
    
        {
        "name" :"gun-ho"
        },
        {
        $push : {
                "language" : "c++"
            }       
        }
    
);
    
 
db.crudtest.update(
    
        {
        "name" :"gun-ho"
        },
        {
        $push : {
                "language" : {
                    $each : ["c","python"]
                }
            }       
        }
    
);
 
cs

삭제는 다음과 같이 하면된다. 
1
2
 
db.crudtest.remove() 
cs

다음에는 find에 대해 알아보겠다. 


posted by 제스트
:
개발관련/MongoDB 2015. 10. 30. 13:45

몽고 db는 기본적으로 json 구조를 쓰며 js와 매우 흡사한 형태(?)로 query 를 날린다. 

내부 api를 이용하여 만드는 구조인듯 보인다. 

머 몽고 db역시 document 구조라 lucene과 비슷한 형태 

Collection은 table, document 는 일종의 row , column은 field로 칭한다. 


다음과 같이 쿼리를 날리면 특정 db를 사용하게 된다. 만약 db가 없으면 생성하게 된다. 

1
2
use testDB
 
cs

insert 시 db.사용할 컬렉션.insert() 를 하면 row가 생성된다. 이때, 컬렉션이 존재 하지 않으면 생성 하면서 저장하게 된다. 

type은 string, date, double 를 지원한듯 보인다.  

1
2
3
4
5
6
7
8
9
10
11
//insert query 
db.userCollection.insert(
 {
     "user":"zest133",
     "pwd" :"zest133",
     "name" :"zest133",
     "email": "zest133@test.com",
     "date" : new Date()
 }
)
 
cs


색인 컬럼은 다음과 같이 설정. 

1
2
3
4
5
6
7
//insert index
 db.userCollection.ensureIndex(
    {
        "user" : 1
    }
 )
 
cs


배열 색인은 다음과 같이 설정. 

1
2
3
4
5
6
  //create array index   
 db.userCollection.createIndex(
    {
        "family" : 1
    }
 )              
cs

createIndex를 사용하여, 특정 json array 컬럼 :1 을 하면된다. 재미난 점은 배열안에 값들이 내부적으로 색인이 된다. 


posted by 제스트
:
개발관련/MongoDB 2015. 10. 30. 10:20

압축 해제하고 서버 실행하면 끝이다.

서버 실행할때 커맨드 라인으로 옵션을 입력하거나 미리 설정파일을 만들어 놓고 사용 할 수 있다.


Mongo 설정 파일 yml 구조를 사용.

tab 없이 스페이스로만 영역을 설정. 머 이런것들 어려우니 작업후 yaml validator로 검증하는게 빠르다.


단일 서버 실행용.

linux 특정 위치에 특정 설정 파일을 생성.

ex) vi mongo.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 
#yml 파일이 존재 하지 않으면 /var/local/mongdb/data 에 data를 저장. (경로도 마찬가지로 없으면 default 경로에 저장.)
#log역시 설정 정보가  없으면 /var/local/mongdb/logs/log.log에 저장.  
#net - network 설정#하위 구조로 bindIp와 port를 설정한다. 
#bindIP는 mongoDB 자신의 ip를 설정. 
#port는 mongDB 의 port를 설정. 
net: 
bindIp: "192.168.0.70" 
 port: 35001
#processManagement - 실행 옵션. 
#fork 는 백그라운드 옵션. 
processManagement: 
 fork: true
#storage - data 저장 경로를 설정. 
#dbpath - data를 저장할 실제 경로. 
#journal - data를 쓰기 전 , data write query를 파일에 저장하는 옵션. (일종의 검증, 복구를 위한 작업인듯...) 
# enabled - journal 을 쓸지 말지의 설정.
storage: 
 dbPath: /root/mongo/data/repl1 
 journal:   
  enabled: true
#destination: file, syslog 2가지 옵션 사용 가능
#file로 선언하면 path 옵션을 필수로 넣어서 경로를 직접 설정
#syslog로 선언하면 경로 설정 없이 디폴트 로그파일에 저장
##verbosity: 로그 기록 레벨
# default : 0
# 0 ~ 5 숫자 값으로 레벨 구분
# 0 : all
# 1 : debug,
# 2: information
# 3: warning
# 4: errorm
# 5: fatalsystem
systemLog:
 verbosity: 1 
 destination: file 
 logAppend: true 
 path: /root/mongo/log/repl_log1.log
cs

마지막으로 실행해보자. 

./bin/mongd -f mongo.yml

posted by 제스트
: