MongoDB建立使用者和Java連線MongoDB
阿新 • • 發佈:2018-12-24
> use test switched to db test > db.createUser({user:"xiuye",pwd:"123456",roles:[]}) Successfully added user: { "user" : "xiuye", "roles" : [ ] } > show tables; system.users system.version > db.system.users.find().pretty() { "_id" : "admin.xiuye", "user" : "xiuye", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "eMiuYT0baIMbnTdsAoszlQ==", "storedKey" : "cz8/EZnKAy4m26jzZUjOXnF5Fzs=", "serverKey" : "RkzXXwQpPi1m0HNwmwQ+thEwmtU=" } }, "roles" : [ ] }
Java連線MongoDB和增查改刪:
package com.xiuye.mongodb; import java.util.ArrayList; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; public class MongoDBOp1 { public static void main(String[] args) { try{ //直接能連線mongodb MongoClient mongoClient = new MongoClient("localhost",27017); log("連線mongodb成功!"); //準備使用使用者賬號連線 ServerAddress serverAddress = new ServerAddress("localhost", 27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //mongodb預設不需要使用者名稱和密碼就可以登入 //雖然能連線但是後面的操作會報錯!還是建立一個吧 //資料庫必須與使用者賬號一致,也就是test資料庫中建立了使用者 MongoCredential credential = MongoCredential.createScramSha1Credential("xiuye", "test", "123456".toCharArray()); List<MongoCredential> credentials = new ArrayList<>(); credentials.add(credential); mongoClient = new MongoClient(addrs,credentials); //資料庫的名字也可以是任意的!哪怕不存在,也可以!但不能為空 //如果沒有資料庫,會自動建立一個(僅限於直接localhost連線) //每個資料庫,必須建立使用者,才能使用使用者賬號登入.向下面這樣 //>use test //>db.createUser({user:"xiuye",pwd:"123456",roles:[]}) //> MongoDatabase mongoDatabase = mongoClient.getDatabase("test"); log("獲取資料庫成功!"); //重複建立會報錯 //Collection就相當於關係型資料庫表 mongoDatabase.createCollection("Java"); log("集合建立成功!"); MongoCollection<Document> collection = mongoDatabase.getCollection("Java"); //文件相當於資料庫表的一條記錄 Document doc = new Document("title","文件") .append("content", "文件相當於資料庫表的一條記錄") .append("links", "100") .append("key", "1"); List<Document> docs = new ArrayList<Document>(); docs.add(doc); //插入多個文件(多條記錄) collection.insertMany(docs); log("插入一個文件成功!"); //查詢所有文件 FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ log("得到的文件內容:"+mongoCursor.next().toString()); } //更新文件內容 collection.updateMany(Filters.eq("links","100"), new Document("$set",new Document("links","333"))); findIterable = collection.find(); mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ log("更新的文件內容:"+mongoCursor.next().toString()); } //刪除一條記錄 collection.deleteMany(Filters.eq("key","1")); } catch(Exception e){ e.printStackTrace(); } } static void log(String s){ System.out.println(s); } }
Java控制檯輸出結果:
一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} 連線mongodb成功! 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Cluster created with settings {hosts=[localhost:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Adding discovered server localhost:27017 to client view of cluster 獲取資料庫成功! 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Cluster description not yet available. Waiting for 30000 ms before timing out 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Opened connection [connectionId{localValue:1, serverValue:296}] to localhost:27017 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 7, 1]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3176178} 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Opened connection [connectionId{localValue:2, serverValue:297}] to localhost:27017 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 7, 1]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1075557} 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Discovered cluster type of STANDALONE 一月 16, 2018 11:23:29 下午 com.mongodb.diagnostics.logging.JULLogger log 資訊: Opened connection [connectionId{localValue:3, serverValue:298}] to localhost:27017 插入一個文件成功! 得到的文件內容:Document{{_id=5a5e170c0e11e61e5c66b7d1, title=文件, content=文件相當於資料庫表的一條記錄, links=333}} 得到的文件內容:Document{{_id=5a5e17f80e11e62dfc285690, title=文件, content=文件相當於資料庫表的一條記錄, links=333, key=1}} 得到的文件內容:Document{{_id=5a5e18f10e11e62da4c34ebf, title=文件, content=文件相當於資料庫表的一條記錄, links=100, key=1}} 更新的文件內容:Document{{_id=5a5e170c0e11e61e5c66b7d1, title=文件, content=文件相當於資料庫表的一條記錄, links=333}} 更新的文件內容:Document{{_id=5a5e17f80e11e62dfc285690, title=文件, content=文件相當於資料庫表的一條記錄, links=333, key=1}} 更新的文件內容:Document{{_id=5a5e18f10e11e62da4c34ebf, title=文件, content=文件相當於資料庫表的一條記錄, links=333, key=1}}
MongoDB前後的集合變化:
> show tables;
Java
mycol
> db.Java.find().pretty()
{
"_id" : ObjectId("5a5e170c0e11e61e5c66b7d1"),
"title" : "文件",
"content" : "文件相當於資料庫表的一條記錄",
"links" : "333"
}
{
"_id" : ObjectId("5a5e17f80e11e62dfc285690"),
"title" : "文件",
"content" : "文件相當於資料庫表的一條記錄",
"links" : "333",
"key" : "1"
}
> show tables;
Java
mycol
> db.Java.find().pretty()
{
"_id" : ObjectId("5a5e170c0e11e61e5c66b7d1"),
"title" : "文件",
"content" : "文件相當於資料庫表的一條記錄",
"links" : "333"
}