[ MongoDB ] STS에서 MongoDB연동 및 데이터 추출
STS에서 MongoDB 메이븐 의존 주입
MVNRepository에서 MongoDB Java Driver 검색 후
버전을 선택하고 Maven dependency를 pom.xml에 추가해주고
Maven Update를 해주면 된다.
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
|
STS에서 MongoDB 서버의 데이터 추출하기
data.jsp
<%@page import="com.mongodb.client.MongoCursor"%>
<%@page import="com.mongodb.client.MongoCollection"%>
<%@page import="com.mongodb.MongoClient"%>
<%@page import="org.bson.Document"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String[] cities = new String[]{"서울", "인천", "대전", "대구", "부산",
"제주", "경기", "전라", "경상", "충청", "강원"};
String[] tastes = new String[]{"진보", "보수", "중도"};
List<Document> list = new ArrayList<>();
for(int i=0; i<10000; i++) {
Document d = new Document();
d.put("area", cities[(int)(Math.random() * cities.length)]);
d.put("age", 15 + (int)(Math.random() * 60));
d.put("gender", Math.random() > 0.5? "male" : "female");
d.put("taste", tastes[(int)(Math.random() * tastes.length)]);
list.add(d);
}
%>
|
example_01.jsp
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="org.bson.Document"%>
<%@page import="com.mongodb.client.MongoCollection"%>
<%@page import="com.mongodb.MongoClient"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
MongoClient client = new MongoClient ("192.168.10.16", 27017);
MongoCollection collection = client.getDatabase("brent").getCollection("infos");
// db.컬렉션명.count({});
// Example_01. 성향별 진보 vs (보수 + 중도) 추출
Document ex01Condition1 = new Document();
ex01Condition1.put("taste", "진보");
Document ex01Condition2 = new Document();
Document bjCondition = new Document();
List<String> li = new ArrayList<>();
li.add("보수");
li.add("중도");
bjCondition.put("$in", li);
ex01Condition2.put("taste", bjCondition);
long jinCnt = collection.count(ex01Condition1);
out.println("진보 : " + jinCnt + "<br/>");
long bjCnt = collection.count(ex01Condition2);
out.println("보수/중도 : " + bjCnt + "<br/>");
// Example_01. 남성이며 진보와, 여성이며 진보 따로 추출
Document ex02Condition1 = new Document();
ex02Condition1.put("gender", "male");
ex02Condition1.put("taste", "진보");
Document ex02Condition2 = new Document();
ex02Condition2.put("gender", "female");
ex02Condition2.put("taste", "진보");
out.println("<hr/>");
long cnt1 = collection.count(ex02Condition1);
out.println("남자이며 진보 : " + cnt1 + "<br/>");
long cnt2 = collection.count(ex02Condition2);
out.println("여자이며 진보 : " + cnt2 + "<br/>");
client.close();
%>
|
댓글
댓글 쓰기