갈림길 이정표

[java] MongoDB 구동 및 java에서 불러오기 (feat. CRUD) 본문

Programming Language/Java 마스터하기(feat. 이것이 자바다)

[java] MongoDB 구동 및 java에서 불러오기 (feat. CRUD)

이몽뇽 2020. 8. 10. 10:04
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use test
switched to db test
> use test
switched to db test
> db
test
> show collections
> ;
> show collections;
> db.stats();
{
        "db" : "test",
        "collections" : 0,
        "views" : 0,
        "objects" : 0,
        "avgObjSize" : 0,
        "dataSize" : 0,
        "storageSize" : 0,
        "totalSize" : 0,
        "indexes" : 0,
        "indexSize" : 0,
        "scaleFactor" : 1,
        "fileSize" : 0,
        "fsUsedSize" : 0,
        "fsTotalSize" : 0,
        "ok" : 1
}
> show collections;
> show tables;
> exit
bye
C:\Users\KITCOOP>mongo
MongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("d3da10cc-c029-47a9-9415-f8db0f2c9dac") }
MongoDB server version: 4.4.0
---
The server generated these startup warnings when booting:
        2020-08-10T09:47:04.138+09:00: ***** SERVER RESTARTED *****
        2020-08-10T09:47:14.724+09:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> use tset
switched to db tset
> db
tset
> db.abc.insert({user name:'smith'})
uncaught exception: SyntaxError: missing : after property id :
@(shell):1:20
> db.abc.insert({username:'smith'})
WriteResult({ "nInserted" : 1 })
> show collections;
abc
> db.abc.insert({username:'tom',juso:'seoul'})
WriteResult({ "nInserted" : 1 })
> show collections;
abc
> var m = {username:'john',juso:'jeju'}
> db.anc.insert(m)
WriteResult({ "nInserted" : 1 })
> db.abc.find()
{ "_id" : ObjectId("5f309be3fac60cc08f98809b"), "username" : "smith" }
{ "_id" : ObjectId("5f309c21fac60cc08f98809c"), "username" : "tom", "juso" : "seoul" }
> db.abc.insert(m)
WriteResult({ "nInserted" : 1 })
> db.abc.find()
{ "_id" : ObjectId("5f309be3fac60cc08f98809b"), "username" : "smith" }
{ "_id" : ObjectId("5f309c21fac60cc08f98809c"), "username" : "tom", "juso" : "seoul" }
{ "_id" : ObjectId("5f309cb1fac60cc08f98809e"), "username" : "john", "juso" : "jeju" }
> db.abc.insert({x:1, y:new Date()})
WriteResult({ "nInserted" : 1 })
> db.abc.find()
{ "_id" : ObjectId("5f309be3fac60cc08f98809b"), "username" : "smith" }
{ "_id" : ObjectId("5f309c21fac60cc08f98809c"), "username" : "tom", "juso" : "seoul" }
{ "_id" : ObjectId("5f309cb1fac60cc08f98809e"), "username" : "john", "juso" : "jeju" }
{ "_id" : ObjectId("5f309cd7fac60cc08f98809f"), "x" : 1, "y" : ISODate("2020-08-10T01:03:19.430Z") }
> db.abc.drop
function(options = {}) {
    const cmdObj = Object.assign({drop: this.getName()}, options);
    ret = this._db.runCommand(cmdObj);
    if (!ret.ok) {
        if (ret.errmsg == "ns not found")
            return false;
        throw _getErrorWithCode(ret, "drop failed: " + tojson(ret));
    }
    return true;
}
> true;
true
> show collections;
abc
> use mydb
switched to db mydb
> db
mydb
> use tset
switched to db tset
> db.abc.drop()
true
> db
tset
> use mydb
switched to db mydb
> db.myuser.insert({name:'홍길동', age:20, job:'프로그래머'})
WriteResult({ "nInserted" : 1 })
> db.myuser.insert({name:'고길동', age:22, job:'데이터사이언티스트'})
WriteResult({ "nInserted" : 1 })
> db.myuser.insert({name:'신길동', age:22, job:'웹디자이너'})})})})})
WriteResult({ "nInserted" : 1 })
> db.myuser.find()
{ "_id" : ObjectId("5f309e76fac60cc08f9880a0"), "name" : "홍길동", "age" : 20, "job" : "프로그래머" }
{ "_id" : ObjectId("5f309e8ffac60cc08f9880a1"), "name" : "고길동", "age" : 22, "job" : "데이터사이언티스트" }
{ "_id" : ObjectId("5f309eabfac60cc08f9880a2"), "name" : "신길동", "age" : 22, "job" : "웹디자이너" }
>
package pack1;

import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.*;	//MongoCollection Document 가 들어 있는 곳

public class DBTest9_Mongodb {

	public static void main(String[] args) {
		String mongo_ip = "127.0.0.1";
		int mongo_port = 27017;
		String db_name ="mydb";
		
		// NoSQL : MongoDB와 연동
		MongoClient client = new MongoClient(new ServerAddress(mongo_ip, mongo_port));
		MongoDatabase db = client.getDatabase(db_name);
		
		//Collection(sql의 record)
		MongoCollection<Document> collection = db.getCollection("myuser");
		System.out.println("◎자료 건수 : " + collection.countDocuments());
		
		System.out.println();
		
		//1개의 document(sql의 row) 읽기
		Document doc = collection.find().first();
		System.out.println("◎첫번째 자료: " + doc.toJson());
		
		System.out.println();
		
		//자료 추가
		Document ins_doc = new Document("name","나이스").append("age", 30).append("job", "DB관리자");
		collection.insertOne(ins_doc);
		
		//전체 자료 출력
		MongoCursor<Document> cursor = collection.find().iterator();
		try {
			System.out.println("◎전체 자료 출력");
			while(cursor.hasNext()) {
				String jsonResult = cursor.next().toJson();
				System.out.println(jsonResult);
			}
			System.out.println();
			System.out.println("◎데이터만 출력\n------------------");
			cursor = collection.find().iterator();
			while(cursor.hasNext()) {
				Document doc2 = cursor.next();
				System.out.println("이름: " + doc2.get("name"));
				System.out.println("나이: " + doc2.get("age"));
				System.out.println("직업: " + doc2.get("job"));
				System.out.println();
			}
			
		} catch (Exception e) {
			System.out.println("err: " + e);
		}
	}

}
Comments