基于Java訪問數據庫
更新時間 2023-08-29 15:14:30
最近更新時間: 2023-08-29 15:14:30
分享文章
本頁介紹了使用如何使用Java訪問文檔數據庫服務。
訪問DataBase
當已經有一個初始化好的MongoClient后,通過如下方式來訪問一個database,示例如下:
MongoDatabase memberInfoDatabase = mongoClient.getDatabase("MemberInfo");
訪問集合
當獲取一個MongoDatabase實例后,可以通過如下命令來得到要獲取的集合:
MongoCollection<Document> coll = memberInfoDatabase.getCollection("gold_member");
顯示的創建一個集合
也可以通過 createCollection()方法顯示的創建一個集合,并在創建時候指定該集合的屬性。
memberInfoDatabase.createCollection("testCollection", new CreateCollectionOptions().sizeInBytes(200000));
插入數據
Document doc0 = new Document("name", "萬三")
? ? ? .append("age", 30)
? ? ? .append("sex", "male");
?
Document doc1 = new Document("name", "劉亞")
? ? ? .append("age", 42)
? ? ? .append("sex", "male");
?
Document doc2 = new Document("name", "王瑩")
? ? ? .append("age", 22)
? ? ? .append("sex", "female");
?
List<Document> documents = new ArrayList<>();
documents.add(doc0);
documents.add(doc1);
documents.add(doc2);
goldMemberCollection.insertMany(documents);
刪除數據
goldMemberCollection.deleteOne(eq("name", "劉亞"));
刪除表
MongoCollection<Document> collection = memberInfoDatabase.getCollection("test");
collection.drop();
讀數據
MongoCursor<String> cursor = (MongoCursor<String>) goldMemberCollection.find();
while (cursor.hasNext()) {
? ?Object result = cursor.next();
}
cursor.close();
帶過濾條件的查詢
MongoCursor<String> cursorCondition = (MongoCursor<String>)goldMemberCollection.find(
? ? ? ?new Document("name","zhangsan")
? ? ? ? ? ? ? .append("age", 5));
while (cursorCondition.hasNext()) {
? ?Object result = cursorCondition.next();
}
cursorCondition.close();
運行命令
執行buildInfo和collStats:
MongoClient mongoClientShell = (MongoClient) MongoClients.create();
MongoDatabase database = mongoClientShell.getDatabase("MemberInfo");
?
Document buildInfoResults = database.runCommand(new Document("buildInfo", 1));
System.out.println(buildInfoResults.toJson());
?
Document collStatsResults = database.runCommand(new Document("collStats", "restaurants"));
System.out.println(collStatsResults.toJson());
創建索引
MongoCollection<Document> collectionTest = memberInfoDatabase.getCollection("gold_member");
collectionTest.createIndex(Indexes.ascending("age"));