azure011328

导航

 

{

“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列)

 

  1. package com.hua;  
  2.   
  3. import org.junit.Test;  
  4. import com.mongodb.MongoClient;  
  5. import com.mongodb.MongoClientURI;  
  6. import com.mongodb.client.MongoCollection;  
  7. import com.mongodb.client.MongoDatabase;  
  8. import org.bson.Document;  
  9. import java.sql.*;  
  10. import java.util.ArrayList;  
  11.   
  12. public class test {  
  13.   
  14.     @Test  
  15.     public void test() throws SQLException{  
  16.         // 设置 MongoDB 连接字符串  
  17.         String connectionString = "mongodb://localhost/Gaozhenhua";  
  18.   
  19.         // 创建 MongoClient  
  20.         MongoClientURI uri = new MongoClientURI(connectionString);  
  21.         MongoClient mongoClient = new MongoClient(uri);  
  22.   
  23.         // 连接到数据库  
  24.         MongoDatabase database = mongoClient.getDatabase("Gaozhenhua");  
  25.   
  26.         // 获取 student 集合  
  27.         MongoCollection<Document> collection = database.getCollection("student");  
  28.   
  29.         // (1) 添加数据  
  30.         Document scofieldDocument = new Document()  
  31.                 .append("name", "scofield")  
  32.                 .append("score", new Document()  
  33.                         .append("English", 45)  
  34.                         .append("Math", 89)  
  35.                         .append("Computer", 100));  
  36.   
  37.         collection.insertOne(scofieldDocument);  
  38.   
  39.         // (2) 获取 scofield 的所有成绩(只显示 score 列)  
  40.         Document query = new Document("name", "scofield");  
  41.         Document projection = new Document("score", 1).append("_id", 0);  
  42.   
  43.         Document scofieldResult = collection.find(query).projection(projection).first();  
  44.         System.out.println("Scofield's score: " + scofieldResult);  
  45.   
  46.         // 关闭连接  
  47.         mongoClient.close();  
  48.     }  
  49. }  

 

posted on 2024-12-13 10:55  淮竹i  阅读(12)  评论(0)    收藏  举报