JAVA操作MongoDB


以下代码仅供参考

提示:下面代码的格式需注意,原题中会有空格在前面,可以与截图做对照

第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"));

在这里插入图片描述


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值