mongoDB练习

2021/10/26 19:09:38

本文主要是介绍mongoDB练习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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集合;

use School

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()

db.student.find().pretty()

 

 

(3)用find()方法查询zhangsan的所有成绩(只显示score列);

db.student.find({name:'zhangsan'},{'score':1})

 

 

(4)修改lisi的Math成绩,改为95。

db.student.update({name:'lisi'},{$set:{'score.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 org.example;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class mongo {

    public static void main(String[] args) {
        MongoCollection<Document> collection = getCollection("School","student");
        insert(collection);
        find(collection);
    }

    public static MongoCollection<Document> getCollection(String dbname,String collectionname){
        MongoClient  mongoClient=new MongoClient("localhost",27017);
        MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);
        MongoCollection<Document> collection = mongoDatabase.getCollection(collectionname);
        return collection;
    }
    public static void insert(MongoCollection<Document> collection){
        try{
            Document doc=new Document("name","scofield").append("score", new Document("English",45).append("Math",89).append("Computer",100));
            collection.insertOne(doc);
            System.out.println("插入成功");
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
    public static void find(MongoCollection<Document> collection){
        try{
            MongoCursor<Document>  cursor= collection.find(new Document("name","scofield")).projection(new Document("score",1)).iterator();
            while(cursor.hasNext()){
                System.out.println(cursor.next().toJson());
            }
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
}

 

 



这篇关于mongoDB练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程