刘一辰的软件工程随笔
石家庄铁道大学信息科学与技术学院
2021年---2022年 第一学期
专 业: 软件工程
课程名称: 大型数据库应用技术
班 级: 信1905-2班
姓 名:刘一辰学号: 20193897
指导教师: 王建民
MongoDB数据库操作
Student文档如下:
{ “name”: “zhangsan”, “score”: { “English”: 69, “Math”: 86, “Computer”: 77 } } { “name”: “lisi”, “score”: { “English”: 55, “Math”: 100, “Computer”: 88 } } |
1.根据上面给出的文档,完成如下操作:
(1)用MongoDB Shell设计出student集合;
(2)用find()方法输出两个学生的信息;
(3)用find()方法查询zhangsan的所有成绩(只显示score列);
(4)修改lisi的Math成绩,改为95。
2.根据上面已经设计出的Student集合,用MongoDB的Java客户端编程,实现如下操作:
(1)添加数据:English:45 Math:89 Computer:100
与上述数据对应的文档形式如下:
{ “name”: “scofield”, “score”: { “English”: 45, “Math”: 89, “Computer”: 100 } } |
(2)获取scofield的所有成绩成绩信息(只显示score列)
package mongodb;
import java.util.Arrays;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import static com.mongodb.client.model.Filters.*;
public class MongoDBTest {
MongoClient client;
MongoDatabase dataBase;
MongoCollection<Document> collection;
@Before
public void init() {
client = new MongoClient("localhost", 27017);
dataBase = client.getDatabase("student");
collection = dataBase.getCollection("student");
}
@Test
public void insert() {
Document doc = new Document();
doc.append("name", "scofield");
Document score = new Document();
score.append("English",45);
score.append("Math",89);
score.append("Computer",100);
doc.append("score",score);
collection.insertOne(doc);
System.out.println("success");
}
@Test
public void find() {
Bson filter = in("name", Arrays.asList("scofield"));
FindIterable<Document> find = collection.find(filter);
find.forEach(new Block<Document>() {
@Override
public void apply(Document t) {
Document d = (Document) t.get("score");
System.out.println(d.toJson());
}
});
}
@Test
public void delete() {
Bson filter = eq("name", "duanjt");
DeleteResult deleteMany = collection.deleteMany(filter);
System.out.println("删除数据:" + deleteMany.getDeletedCount());
}
@Test
public void dropCol() {
collection.drop();
System.out.println("删除成功");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!