|
{ “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 com.hua;
- import org.junit.Test;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoClientURI;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- import org.bson.Document;
- import java.sql.*;
- import java.util.ArrayList;
- public class test {
- @Test
- public void test() throws SQLException{
- // 设置 MongoDB 连接字符串
- String connectionString = "mongodb://localhost/Gaozhenhua";
- // 创建 MongoClient
- MongoClientURI uri = new MongoClientURI(connectionString);
- MongoClient mongoClient = new MongoClient(uri);
- // 连接到数据库
- MongoDatabase database = mongoClient.getDatabase("Gaozhenhua");
- // 获取 student 集合
- MongoCollection<Document> collection = database.getCollection("student");
- // (1) 添加数据
- Document scofieldDocument = new Document()
- .append("name", "scofield")
- .append("score", new Document()
- .append("English", 45)
- .append("Math", 89)
- .append("Computer", 100));
- collection.insertOne(scofieldDocument);
- // (2) 获取 scofield 的所有成绩(只显示 score 列)
- Document query = new Document("name", "scofield");
- Document projection = new Document("score", 1).append("_id", 0);
- Document scofieldResult = collection.find(query).projection(projection).first();
- System.out.println("Scofield's score: " + scofieldResult);
- // 关闭连接
- mongoClient.close();
- }
- }
浙公网安备 33010602011771号