반응형
1. MongoDB와 JAVA 연동
- mongod 인스턴스 및 데이터베이스 연결
// import된 각 패키지들에 대한 설명은 API 문서 참조
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
public class ConnectToDB {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient myclient = new MongoClient("localhost" , 27017);
// 또는 MongoClient myclient = new MongoClient();
System.out.println("Connected to the database successfully");
// Accessing the database (db가 없으면 새로 생성)
MongoDatabase mydb = myclient.getDatabase("sdb");
}
}
- 컬렉션 생성
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
public class ConnectToDB {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient myclient = new MongoClient();
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase mydb = myclient.getDatabase("sdb");
//Creating a collection
mydb.createCollection("sampleCol");
System.out.println("Collection created successfully");
}
}
- 특정 DB 내의 모든 컬렉션 이름 출력
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
. . .
public class ListOfCollection {
public static void main( String args[] ) {
. . .
// Accessing the database
MongoDatabase mydb = myclient.getDatabase("sdb");
// listing all collections
for (String name : mydb.listCollectionNames()) {
System.out.println(name);
}
}
}
- 컬렉션 선택(반환)
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import org.bson.Document;
public class selectingCollection {
public static void main( String args[] ) {
. . .
// Accessing the database
MongoDatabase mydb = myclient.getDatabase("sdb");
// Retrieving a collection
MongoCollection<Document> mycol = mydb.getCollection("sampleCol");
System.out.println("Collection Col selected successfully");
}
}
-컬렉션 제거(drop)
import com.mongodb.client.MongoCollection;
. . .
public class DroppingCollection {
public static void main( String args[] ) {
. . .
// Accessing the database
MongoDatabase mydb = myclient.getDatabase("sdb");
// Retrieving a collection
MongoCollection<Document> mycol = mydb.getCollection("sampleCol");
// Dropping a Collection
mycol.drop();
System.out.println("Collection dropped successfully");
}
}
- document삽입
. . .
import org.bson.Document;
public class insertingDocument {
public static void main( String args[] ) {
. . .
// Retieving a collection
MongoCollection<Document> mycol = mydb.getCollection("sampleCol");
System.out.println("Collection Col selected successfully");
// bson Document 객체 생성
Document mydoc = new Document("title", "MongoDB")
.append("id", 1)
.append("description", "database")
.append("likes", 100)
.append("url", "http://www.tutorialspoint.com/mongodb/")
.append("by", "tutorials point");
mycol.insertOne(mydoc);
System.out.println("Document inserted successfully");
}
}
-컬렉션 내 모든 문서 검색
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import java.util.Iterator;
. . .
public class RetrievingAllDocuments {
public static void main( String args[] ) {
. . .
// Retrieving a collection
MongoCollection<Document> mycol = mydb.getCollection("sampleCol");
// Getting the iterable object
FindIterable<Document> iterDoc = mycol.find();
// Getting the iterator
Iterator it = iterDoc.iterator(); // iterator 반환
int i = 1;
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
-document 수정
import com.mongodb.client.MongoCollection;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
. . .
public class UpdatingDocuments {
public static void main( String args[] ) {
. . .
// Updating a document
mycol.updateOne(Filters.eq("id", 1), Updates.set("likes", 150));
System.out.println("Document update successfully...");
// Getting the iterable object
FindIterable<Document> iterDoc = mycol.find();
// Getting the iterator
Iterator it = iterDoc.iterator(); // iterator 반환
int i = 1;
while (it.hasNext()) {
System.out.println(it.next()); i++;
}
}
}
- document 삭제
import com.mongodb.client.MongoCollection;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
. . .
public class DeletingDocuments {
public static void main( String args[] ) {
. . .
// Deleting a document
mycol.deleteOne(Filters.eq("id", 1)); // deleteMany() 메소드
System.out.println("Document deleted successfully...");
// Getting the iterable object
FindIterable<Document> iterDoc = mycol.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator(); // iterator 반환
while (it.hasNext()) {
System.out.println(it.next()); i++;
}
}
}
-조건에 맞는 특성 문서 검색
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import java.util.Iterator;
. . .
public class RetrievingAllDocuments {
public static void main( String args[] ) {
. . .
// Retrieving a collection
MongoCollection<Document> mycol = mydb.getCollection("sampleCol");
// Finding a document with find(Bson filter) method
// and Getting the iterable object
FindIterable<Document> iterDoc = mycol.find(검색조건); // 커서 반환
//검색 조건 : find() / delete() / update() 조건 표현은 동일
//각종 메소드 활용 가능
. . .
}
}
-----------------------------------------------------------------------------------------------------------------------------------
자바 연동 과제는 따로 보관 ㅎㅎ
반응형
'Database Study > MongoDB' 카테고리의 다른 글
[Mongodb]웹서비스컴퓨팅_11주차_(1)_Sharding (0) | 2019.12.07 |
---|---|
[Mongodb]웹서비스컴퓨팅_10주차 (0) | 2019.12.03 |
[Mongodb]웹서비스컴퓨팅_7주차 (0) | 2019.10.15 |
[Mongodb]웹서비스컴퓨팅_6주차 (0) | 2019.10.01 |
[Mongodb]웹서비스컴퓨팅_5주차 (0) | 2019.09.24 |