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
與上述數據對應的文檔形式如下:
(2)獲取scofield的所有成績成績信息(只顯示score列)
********** ********** ********** ********** ********** ********** ********** ********** ********** ********** **********
(1) 用MongoDB Shell設計出student集合;
啟動mongo服務
show dbs;
使用test數據庫
use test
創建新的集合student並使用
db.createCollection('student');
插入數據
db.student.insert({"name":"zhangsan","score":{"English":69,"Math":86,"Computer":77}}) db.student.insert({"name":"lisi","score":{"English":55,"Math":100,"Computer":88}})
通過可視化工具查看結果
(2)用find()方法輸出兩個學生的信息;
db.student.find();
(3)用find()方法查詢zhangsan的所有成績(只顯示score列);
db.student.find({name:"zhangsan"},{name:0,_id:0});
(4)修改lisi的Math成績,改為95。
db.student.update({name:"lisi"},{$set:{score:{English:55,Math:95,Computer:88}}})
2.根據上面已經設計出的Student集合,用MongoDB的Java客戶端編程,實現如下操作:
(1)添加數據:English:45 Math:89 Computer:100
配置maven依賴(Mongo-4.4.10)
<dependencies> <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.11.1</version> </dependency> </dependencies>
Java代碼
1.連接數據庫
package utils; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; public class DBUtil { public static MongoDatabase getMongoDB() { //創建客戶端 //這里僅僅是連接到了mongoDB服務器 MongoClient client = new MongoClient("localhost",27017); //dbb是數據庫名字,連接到數據庫 MongoDatabase mongoDatabase = client.getDatabase("test"); return mongoDatabase; } }
2.插入數據
public static void insertDoc() { MongoCollection<Document> coll = DBUtil.getMongoDB().getCollection("student"); //注意:一個document只能插入一次。id限制。 Document doc = new Document(); doc.append("name", "scofield"); doc.append("score", Arrays.asList("45","89","100")); // coll.insertOne(doc); List<Document> list = new ArrayList<>(); list.add(doc); coll.insertMany(list);
System.out.println("success");
}
3.主函數
public static void main(String[] args) { insertDoc(); }
運行結果:
(2)獲取scofield的所有成績成績信息(只顯示score列)
按照指定條件查詢
public static void find(){ MongoCollection<Document> coll = DBUtil.getMongoDB().getCollection("student"); try{ Document document = new Document(); document.append("_id",0); document.append("name",0); MongoCursor<Document> cursor= coll.find(new Document("name","scofield")) .projection(document) .iterator(); while(cursor.hasNext()){ System.out.println(cursor.next().toJson()); } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }
主函數
public static void main(String[] args) { find(); }
運行截圖