[Database] MongoDB in Java

게맛살맛게·2021년 12월 24일
0

DB

목록 보기
23/23

Mongo-Java

DB 연결

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

public class MongoJava {
    public static void main(String[] args) {
        try {
            MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
            System.out.println("접속 성공--- ");
            MongoIterable<String> dblist = mongoClient.listDatabaseNames();
            System.out.println("[데이터베이스 리스트]");
            for (String name : dblist)
                System.out.println(name);
            MongoDatabase db = mongoClient.getDatabase("edudb");
            MongoIterable<String> clist = db.listCollectionNames();
            System.out.println("[edudb 데이터베이스의 컬렉션 리스트]");
            for (String name : clist)
                System.out.println(name);
            mongoClient.close();
        } catch (Exception exception) {
            System.err.println(exception.getClass().getName() + ": " + exception.getMessage());
        }
    }
}

로그메세지 해제

import java.util.logging.Level;
import java.util.logging.Logger;
Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
mongoLogger.setLevel(Level.SEVERE);

도큐먼트 읽기

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

import org.bson.Document;

public class SelectMongo1 {
    public static void main(String[] args) {
        try (MongoClient mongoClient = new MongoClient("localhost", 27017);) {  // DB 연결 설정
            MongoDatabase db = mongoClient.getDatabase("edudb");                // DB 지정
            MongoCollection<Document> collection = db.getCollection("book");    // Collection 지정
            MongoCursor<Document> cursor = collection.find().iterator();        // Cursor로 결과 저장
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ":" + e.getMessage());
        }
    }
}

모든 도큐먼트를 읽어오는 다양한 방법

        try (MongoClient mongoClient = new MongoClient("localhost", 27017)) {
            MongoDatabase db = mongoClient.getDatabase("edudb");                // DB 지정
            MongoCollection<Document> collection = db.getCollection("book");    // Collection 지정
            MongoCursor<Document> cursor = collection.find().iterator();
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            System.out.println("--------------------------------");
            cursor = collection.find().iterator();                              // Cursor 활용
            while (cursor.hasNext()) {
                Document doc = cursor.next();
                System.out.println(doc.get("name") + " : " + doc.get("price"));
            }
            System.out.println("--------------------------------");
            Consumer<Document> printConsumer = new Consumer<Document>() {       // Consumer 활용
                @Override
                public void accept(final Document document) {
                    System.out.println(document.toJson());
                }
            };
            collection.find().forEach(printConsumer);
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ":" + e.getMessage());
        }

원하는 도큐먼트를 읽어오는 다양한 방법

        try (MongoClient mongoClient = new MongoClient("localhost", 27017)) {
            System.out.println("--------------------------------");

            MongoDatabase db = mongoClient.getDatabase("edudb");             // DB 지정
            MongoCollection<Document> collection = db.getCollection("book"); // Collection 지정
            Document doc = collection.find().first();
            System.out.println(doc.toJson());                                // Json 형식 출력
            System.out.println("--------------------------------");

            FindIterable<Document> dlist = collection.find(Filters.gt("price", 10000)); // Filters 사용
            for (Document doc1 : dlist)
                System.out.println(doc1.toJson());
            System.out.println("--------------------------------");

            dlist = collection.find(Filters.eq("name", "javascript"));
            for (var doc1 : dlist)
                System.out.println(doc1.toJson());
            System.out.println("--------------------------------");

            dlist = collection.find(Filters.regex("name", "^ja"));
            for (var doc1 : dlist)
                System.out.println(doc1.toJson());
            System.out.println("--------------------------------");

            dlist = collection.find(Filters.and(Filters.gt("price", 10000), Filters.lte("price", 20000)));
            for (Document doc1 : dlist)
                System.out.println(doc1.toJson());
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ":" + e.getMessage());
        }

도큐먼트 삽입

package com.mongo.level1;

import java.util.function.Consumer;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import org.bson.Document;

public class InsertMongo1 {
    public static void main(String[] args) {
        try {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            MongoDatabase db = mongoClient.getDatabase("edudb");
            MongoCollection<Document> collection = db.getCollection("book");

            Document doc = new Document("name", "spring").append("price", "30000");
            collection.insertOne(doc);		// 한개만
            
            List<Document> documents = new ArrayList<Document>();
            for (int i = 1; i <= 10; i++) {
                documents.add(new Document("name", "book" + i).append("price", 10000 * i));
            }
            collection.insertMany(documents);	// 여러개

            Consumer<Document> printConsumer = new Consumer<Document>() {
                @Override
                public void accept(final Document document) {
                    System.out.println(document.toJson());
                }
            };
            collection.find().forEach(printConsumer);
            mongoClient.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

도큐먼트 수정

package com.mongo.level1;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

public class UpdateMongo1 {
    public static void main(String[] args) {

        Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
        mongoLogger.setLevel(Level.SEVERE);
        try {
            MongoClient mongoClient = new MongoClient();
            MongoDatabase db = mongoClient.getDatabase("edudb");
            MongoCollection<Document> collection = db.getCollection("book");

            collection.updateOne(Filters.eq("name", "spring"), Updates.set("price", 29999));
            collection.updateOne(Filters.eq("name", "spark"), Updates.inc("price", 11));
            MongoCursor<Document> cursor = collection.find().iterator();
            while (cursor.hasNext()) {
                Document doc1 = cursor.next();
                System.out.println(doc1.get("name") + " : " + doc1.get("price"));
            }
            mongoClient.close();
        } catch (Exception exception) {
            System.err.println(exception.getClass().getName() + ": " + exception.getMessage());
        }

        try {
            MongoClient mongoClient = new MongoClient();
            MongoDatabase db = mongoClient.getDatabase("edudb");
            MongoCollection<Document> collection = db.getCollection("book");
            Bson filter = Filters.eq("name", "spring");
            Document doc = new Document("name", "SPRING").append("price", 30000);
            collection.replaceOne(filter, doc);

            MongoCursor<Document> cursor = collection.find().iterator();
            while (cursor.hasNext()) {
                Document doc1 = cursor.next();
                System.out.println(doc1.get("name") + " : " + doc1.get("price"));
            }
            mongoClient.close();
        } catch (Exception exception) {
            System.err.println(exception.getClass().getName() + ": " + exception.getMessage());
        }
    }
}

도큐먼트 삭제

package com.mongo.level1;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class DeleteMongo1 {

    public static void main(String[] args) {
        Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
        mongoLogger.setLevel(Level.SEVERE);
        try {
            MongoClient mongoClient = new MongoClient();
            MongoDatabase db = mongoClient.getDatabase("edudb");
            MongoCollection<Document> collection = db.getCollection("book");
            Bson filter = Filters.eq("name", "book1");
            collection.deleteOne(filter);
            MongoCursor<Document> cursor = collection.find().iterator();
            while (cursor.hasNext()) {
                Document doc1 = cursor.next();
                System.out.println(doc1.get("name") + " : " + doc1.get("price"));
            }
            filter = Filters.gt("price", 50000);
            collection.deleteMany(filter);
            cursor = collection.find().iterator();
            while (cursor.hasNext()) {
                Document doc1 = cursor.next();
                System.out.println(doc1.get("name") + " : " + doc1.get("price"));
            }
            mongoClient.close();
        } catch (Exception exception) {
            System.err.println(exception.getClass().getName() + ": " + exception.getMessage());
        }
    }
}
profile
IT 기술블로그

0개의 댓글