SKILL/DATABASE

몽고db JDBC 예제

Jedy_Kim 2018. 1. 3. 19:01
728x90

몽고DB 드라이버 다운로드: http://www.mvnrepository.com/artifact/org.mongodb/mongo-java-driver


. 라이브러리 추가

프로젝트 우클릭 -> build path -> Configure build path

Add External JARs..

mongo 라이브러리 파일 추가 -> OK click

라이브러리 추가 확인

Referenced Libraries에 mongo 라이브러리가 추가되었는지 확인합니다. 


3. 실습

 - 먼저 cmd 프롬프트에 mongod명령어를 통해서 mongoDB Server를 켜놓습니다.

 - MongoClient 클래스 객체를 생성합니다 : 자신의 아이피주소 localhost(=자신의 루프백 아이피 자동입력)와 포트번호를 

    입력합니다 . 해당 객체로 mongoDB Server에 접속합니다

    * 27017 포트 : 서버에서 데이터를 상대방에 넘겨주는 포트번호

    * 27027 포트 : 서버에서 데이터를 상대방으로 부터 받는 포트번호

[출처] [MongoDB] NoSql 몽고디비(MongoDB) (3) Java 연동|작성자 Printf

예제01)기본

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
import org.bson.Document;
 
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
 
public class MongoConnect {
    static Block<Document> printBlock = new Block<Document>(){
        @Override
        public void apply(final Document document) {
            // TODO Auto-generated method stub
            System.out.println(document.toJson());
        }        
    };
    public static void main(String[] args) {
         MongoClient mongoClient = null;
            try{
                //1. 연결(MongoDB의 기본 포트 : 27017)
                mongoClient = new MongoClient("localhost",27017);
                System.out.println("접속 성공"); 
                //2. 사용 데이터베이스 가져오기
                MongoDatabase helloDB = mongoClient.getDatabase("hellomongo");
                //3. 컬렉션 가져오기(Bson 형태)
                MongoCollection<Document> collection = helloDB.getCollection("zipcode");
                //4. 컬렉션에 들어있는 데이터 찾기
//                collection.find().forEach(printBlock);
                
                //<find()의 조건을 이용한 찾기>
                //Filters의 결과는 항상 Bson(Document) Type
                //Filters.eq("city", "NEW YORK")
                // => {city: {$eq:"NEW YORK"}}
                //1. 1개의 조건
//                collection.find(Filters.eq("city", "NEW YORK")).forEach(printBlock);
                //2. 2개 이상의 조건
//                collection.find(Filters.and(Filters.eq("city", "NEW YORK"), Filters.gte("pop", 3000), Filters.gt("_id", "10050"))).forEach(printBlock);
                //Document 클래스 활용
//                Document doc = new Document("pop", new Document("$gte", 100000));
//                collection.find(doc).forEach(printBlock);
//                Document doc2 = new Document("city", "NEW YORK");
//                collection.find(doc2).forEach(printBlock);
                Document doc3 = new Document("state""NY");
//                collection.find(doc3).forEach(printBlock);
//                collection.find(doc3).projection(new Document("city", 1).append("loc", 1)).forEach(printBlock);
                MongoCursor<Document> doc_cursor = collection.find(doc3).iterator();
                //ResultSet처럼 사용할 수 있는 MongoCursor
//                while(doc_cursor.hasNext()){
//                    //get을 이용하여 원하는 값을 꺼낼 수 있음
//                    //키 값처럼 쓰임, 해당 value를 출력
//                    System.out.println(doc_cursor.next().get("city"));
//                }
                collection.find(doc3).sort(new Document("_id"1)).limit(10).forEach(printBlock);
                doc_cursor.close();
                mongoClient.close();
            }catch(Exception e){
                System.out.println(e.getMessage());
            }
    }
}
cs

예제02)Aggregate

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
import java.util.Arrays;
 
import org.bson.Document;
 
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Projections;
 
public class AggregateMain {
    static Block<Document> printBlock = new Block<Document>(){
        // 검색 결과물인 FindIterable 인터페이스 객체를 출력하는 객체
        // Block 인터페이스 : 검색된 하나의 결과물(Document)
        @Override
        public void apply(final Document document) {
            // TODO Auto-generated method stub
            System.out.println(document.toJson());
        }
        
    };
    public static void main(String[] args) {
        MongoClient mClient = new MongoClient("localhost"27017);
        MongoDatabase helloDB = mClient.getDatabase("hellomongo");
        
//        MongoCollection<Document> collection = helloDB.getCollection("employees");
//        MongoCollection<Document> collection = helloDB.getCollection("zipcode");
//        collection.aggregate(
//                Arrays.asList(
//                        Aggregates.match(Filters.eq("state", "NY")),                         
//                        new Document("$project", new Document("_id", 1).append("state", 1).append("city", 1))                        
//                )
//        ).forEach(printBlock);
//        
//        collection.aggregate(
//                Arrays.asList(
//                        Aggregates.match(Filters.eq("deptno", 10)),
//                        Aggregates.group("$job", Accumulators.sum("count", 1))                        
//                )
//        ).forEach(printBlock);
        
//        collection.aggregate(
//                Arrays.asList(
//                        Aggregates.project(
//                                Projections.fields(
//                                        Projections.excludeId(),    //ID는 project에서 제외
//                                        Projections.include("ename", "detpno")
//                                )
//                        )                        
//                )
//        ).forEach(printBlock);
        MongoCollection<Document> collection = helloDB.getCollection("position");
        collection.aggregate(
                Arrays.asList(
                        Aggregates.project(
                                Projections.fields(                                
                                        Projections.include("datatype"),
                                        Projections.computed(
                                                "pos",
                                                //배열에서                         pos_name 배열에서 0번째 인덱스
                                                new Document("$arrayElemAt", Arrays.asList("$pos_name"0))
                                        )
                                )
                        )                        
                )
        ).forEach(printBlock);        
        
        
        
    }
}
cs


예제03)CRUD

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
97
import org.bson.Document;
 
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.Updates;
 
public class CRUDMain {
    static Block<Document> printBlock = new Block<Document>(){
 
        @Override
        public void apply(final Document document) {
            // TODO Auto-generated method stub
            System.out.println(document.toJson());
        }        
    };
    public static void main(String[] args) {
        MongoClient mClient = new MongoClient("localhost"27017);
        MongoDatabase helloDB = mClient.getDatabase("hellomongo");
        MongoCollection<Document> collection = helloDB.getCollection("employees");
//        Document document = new Document("empno", "8888")
//                .append("ename", "t_name")
//                .append("job", "t_job")
//                .append("hiredate", "03-01-2018")
//                .append("sal", 50)
//                .append("deptno", 0);
//        collection.insertOne(document);
        
//        Document doc1 = new Document("empno", "9999")
//                .append("ename", "t_name")
//                .append("job", "t_job")
//                .append("hiredate", "03-01-2018")
//                .append("sal", 50)
//                .append("deptno", 1);
//         
//        
//        Document doc2 = new Document("empno", "5555")
//                .append("ename", "t_name")
//                .append("job", "t_job")
//                .append("hiredate", "03-01-2018")
//                .append("sal", 50)
//                .append("deptno", 2);         
//        
//        Document doc3 = new Document("empno", "2222")
//                .append("ename", "t_name")
//                .append("job", "t_job")
//                .append("hiredate", "03-01-2018")
//                .append("sal", 50)
//                .append("deptno", 3);
//        List<Document> docs = new ArrayList<>();
//        docs.add(doc1);
//        docs.add(doc2);
//        docs.add(doc3);
//        collection.insertMany(docs);
//        collection.find().forEach(printBlock);
        
        //Update
//        collection.updateOne(    //데이터 하나만 바꿈
//                Filters.eq("empno", "2222"),    //조건
//                // combine : 수정할 내용
//                Updates.combine(Updates.set("ename", "up_name"),
//                // currentDate : 수정할 시간
//                Updates.currentDate("lastModifyfield")),
//                                //맞는 조건이 없으면 필드 insert //제약조건 유지. 
//                new UpdateOptions().upsert(true).bypassDocumentValidation(true)    
//        );    
        
        //조건에 맞는 여러 document 수정
//        collection.updateMany(
//                Filters.eq("empno", "9999"),
//                Updates.combine(Updates.set("sal", 0), Updates.currentDate("lastModifyField"))                
//        );
//        collection.find().forEach(printBlock);
        
        //save (replaceOne)
        //update가 필드단위의 수정이라면,
        //save는 document단위의 수정    
        //동일한 Document의 필드를 바꿈
//        collection.replaceOne(
//                Filters.eq("empno", "2222"),
//                new Document("ename", "s_name")
//                .append("sal", 1000)
//                .append("dept", 100)
//        );
//        collection.find().forEach(printBlock);
        //조건에 부합하는 것 한개만 삭제
//        collection.deleteOne(Filters.eq("enano", "8888"));
        //조건에 부합하는 것 모두 삭제
        collection.deleteMany(Filters.eq("ename""s_name"));
        collection.find().forEach(printBlock);
        
        mClient.close();
    }
}
cs


반응형

'SKILL > DATABASE' 카테고리의 다른 글

몽고db 샤드, 리플리카  (0) 2018.01.05
몽고DB  (0) 2018.01.04
모델링  (0) 2018.01.03
몽고db 실습예제  (0) 2018.01.02
자바 jdbc 설정  (0) 2017.12.31