基于Java访问数据库 本页介绍了使用如何使用Java访问文档数据库服务。 访问DataBase 当已经有一个初始化好的MongoClient后,通过如下方式来访问一个database,示例如下: MongoDatabase memberInfoDatabase mongoClient.getDatabase("MemberInfo"); 访问集合 当获取一个MongoDatabase实例后,可以通过如下命令来得到要获取的集合: MongoCollection coll memberInfoDatabase.getCollection("goldmember"); 显示的创建一个集合 也可以通过 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 documents new ArrayList<>(); documents.add(doc0); documents.add(doc1); documents.add(doc2); goldMemberCollection.insertMany(documents); 删除数据 goldMemberCollection.deleteOne(eq("name", "刘亚")); 删除表 MongoCollection collection memberInfoDatabase.getCollection("test"); collection.drop(); 读数据 MongoCursor cursor (MongoCursor ) goldMemberCollection.find(); while (cursor.hasNext()) { Object result cursor.next(); } cursor.close(); 带过滤条件的查询 MongoCursor cursorCondition (MongoCursor )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());