以下代码仅供参考
提示:下面代码的格式需注意,原题中会有空格在前面,可以与截图做对照
第1关:Java 操作 MongoDB 数据库(一)
编程要求
根据提示,在右侧编辑器 Begin-End 中补充代码,将以下文档插入 mydb1 数据库的 test1 集合中。
测试说明
平台会对你编写的代码进行测试,代码各部分功能成功实现会输出 test1 集合的内容,具体请看测试集。
代码如下:
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb1");
代码如下:
mongoDatabase.createCollection("test1");
代码如下:
MongoCollection<Document> collection = mongoDatabase.getCollection("test1");
代码如下:
Document document1 = new Document();
document1.append("_id","1");
document1.append("name","Xiaoming");
document1.append("sex","man");
document1.append("age",21);
List<Document> documents = new ArrayList<Document>();
documents.add(document1);
collection.insertMany(documents);
第2关:Java 操作 MongoDB 数据库(二)
编程要求
根据提示,在右侧编辑器 Begin-End 中补充代码(请勿删除原有代码框架)。
将以下文档插入 mydb2 数据库的 test2 集合中;
检索 test2 中的所有文档;
更新 Xiaohong 的信息为23岁;
删除 Xiaoliang 的信息。
测试说明
平台会对你编写的代码进行测试,代码各部分功能成功实现会输出相应的的内容,具体请看测试集。
代码如下:
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb2");
mongoDatabase.createCollection("test2");
代码如下:
MongoCollection<Document> collection = mongoDatabase.getCollection("test2");
Document document1 = new Document();
document1.append("_id","1");
document1.append("name","Xiaoming");
document1.append("sex","man");
document1.append("age",21);
Document document2 = new Document();
document2.append("_id","2");
document2.append("name","Xiaohong");
document2.append("sex","woman");
document2.append("age",20);
Document document3= new Document();
document3.append("_id","3");
document3.append("name","Xiaoliang");
document3.append("sex","man");
document3.append("age",22);
List<Document> documents = new ArrayList<Document>();
documents.add(document1);
documents.add(document2);
documents.add(document3);
collection.insertMany(documents);
代码如下:
collection.updateMany(Filters.eq("name","Xiaohong"), new Document("$set",new Document("age",23)));
代码如下:
collection.deleteMany(Filters.eq("name","Xiaoliang"));