MongoDB的基本使用及java对MongoDB的基本增删改查

MongoDB的特点

  • MongoDB 是文档存储数据库,存储结构灵活
  • MongoDB 支持复杂查询操作、支持序列
  • MongoDB 采用C++开发,可以做分布式扩展
  • MongoDB 采用BSON格式存储
  • MongoDB 支持js引擎,可以编写js语句块

安装和使用

1.以管理员身份运行cmd.exe进入命令行控制台,启动mongod服务端,

mongod --dbpath F:\mongodb\data --logpath F:\mongodb\logs\a.log
启动mongo客户端:mongo


2.将服务器启动做成Window服务

          以管理员身份运行cmd.exe进入命令行控制台

  • 执行创建MongoDB服务命令

    mongod --dbpath F:\mongodb\data --logpath F:\mongodb\logs\a.log --serviceName MongoDB --install
    
  • 启动和停止MongoDB服务

    net start MongoDB
    net stop MongoDB
    
  • 删除MongoDB服务(先停止服务)

    sc delete MongoDB

MongoDB操作命令

库操作(用户空间)

  • show dbs //查看有哪些库
  • use xxx //创建使用某个库
  • db.dropDatabase() //删除当前库

集合操作(表)

  • show collections //查看当前库有哪些集合
  • db.xxx.insert() //插入记录时自动创建集合
  • db.xxx.drop() //删除集合

记录操作(记录)

  • db.xxx.insert() //插入记录

    db.emp.insert({"empno":1001,"ename":"tom"})
    
    db.dept.insert([{"dno":111,"dname":"ui"},{"dno":112,"dname":"h5"}])
    
    for(var i=1;i<100;i++){
        db.dept.insert({"dno":i,"dname":"java"+i});
    };
    
  • db.xxx.find() //查询记录

    db.emp.find()
    
    db.dept.find({"dno":50})
    
    db.dept.find({"dno":{$gt:90}})
    
    db.dept.find({"dname":/h/})
    
  • db.xxx.update() //更新记录

    //整体更新
    db.dept.update({"dno":2},{"dname":"php"})
    
    //局部更新
    db.dept.update({"dno":3},{$set:{"dname":"h5"}})
    
    //更新多条记录,第三个false表示没有符合记录不插入;true表示插入。第四个参数true表示多行更新;false表示单行
    db.dept.update({"dno":{$lt:10}},{$set:{"dname":"JAVA"}},false,true)
    
  • db.xxx.remove() //删除记录

    db.emp.remove({})
    
    db.dept.remove({"dno":1})
    
    db.dept.remove({"dno":{$gt:50}})
    

其他操作

  • 统计

    //统计dept记录数量
    db.dept.count()
    
    //获取dname值,去重
    db.dept.distinct("dname")
    
  • 排序

    //按dname降序排列
    db.dept.find().sort({"dname":-1})
    
    //按dname升序排列
    db.dept.find().sort({"dname":1})
    
  • 分页

    //获取前5条记录
    db.dept.find().limit(5)
    
    //跳过5条再取5条(取6-10)
    db.dept.find().skip(5).limit(5)
    
  • 索引

    db.dept.ensureIndex({"dname":1})        
    
    db.dept.dropIndexes()
    
    db.dept.find({"dname":"java99999"}).explain("executionStats")

Java访问MongoDB

基于mongo-java包基本访问

API介绍

- MongoClient  连接对象  Mongo
- MongoDatabase 库对象   DB
- MongoCollection 集合对象  DBCollection
- MongoCursor 查询结果集对象 DBCoursor
- Document 记录对象  DBObject
public class MongoDBTest {
    @Test
    public void test1() {
        MongoClient m = new MongoClient("localhost", 27017);
        MongoIterable<String> dbs = m.listDatabaseNames();// 查询数据库列表
        MongoCursor<String> iterator = dbs.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
    //查询全部测试
    @Test
    public void test2() {
        MongoClient m = new MongoClient("localhost", 27017);
        MongoDatabase dbs = m.getDatabase("java20");// 查询数据库名
        /// 查询数据库表 /java20.java20
        MongoCollection<Document> collection = dbs.getCollection("java20");
        MongoCursor<Document> cusor = collection.find().iterator();// 查询数据
        // 使用迭代器进行迭代
        while (cusor.hasNext()) {
            Document next = cusor.next();
            Object object = next.get("user");
            String name = next.getString("name");
            String pwd = next.getString("pwd");
            System.out.println("userID" + object + "   name:  " + name + "||  :Password:" + pwd);
        }

    }
    
    //过滤查询测试
    @Test
    public void test3() {
        MongoClient m = new MongoClient("localhost", 27017);
        MongoDatabase database = m.getDatabase("java20");
        MongoCollection<Document> collections = database.getCollection("java20");
        // Bson filter = Filters.lt("dno", 10);//{"dno":{$lt:10}}
        Bson lt = Filters.lt("user", 10);
        MongoCursor<Document> documents = collections.find(lt).iterator();
        while (documents.hasNext()) {
            Document d = documents.next();
            Object userid = d.get("user");
            Object name = d.get("name");
            Object pwd = d.get("pwd");
            System.out.println("id为:" + userid + " 姓名是:" + name + "  密码是:" + pwd);
        }
        m.close();

    }
    //插入测试
    @Test
    public void test4() {
        MongoClient m = new MongoClient();
        MongoDatabase database = m.getDatabase("java20");//使用java20的一个数据库
        MongoCollection<Document> coll= database.getCollection("emp");//查找emp的表,如果没有emp表就创建一个表
        
        Document doc=new Document();
        doc.put("eno", 1003);
        doc.put("ename", "being");
        doc.put("salary", 5755);
        coll.insertOne(doc);
    }
    
    //局部更新
    @Test
    public void Test5(){
        MongoClient m=new MongoClient("localhost",27017);
        MongoDatabase database = m.getDatabase("java20");//获取当前数据库的库名
        MongoCollection<Document> emp = database.getCollection("emp");//
        
        Bson where = Filters.eq("eno", 1002);//
        
        Document doc=new Document();
        doc.put("salary", 8356); //{"salary":4646}
        Document up=new Document();
        up.put("$set", doc);     //{$set:{"salary":5657}}
        //这里使用了更新
        emp.updateOne(where, up);
        m.close();
    }
    
    //全部更新
    @Test
    public void Test6(){
        MongoClient m=new MongoClient("localhost",27017);
        MongoDatabase database = m.getDatabase("java20");
        MongoCollection<Document> emp = database.getCollection("emp");
        Bson eq = Filters.eq("eno", 1003);
        //System.out.println(eq);  Filter{fieldName='eno', value=1003}
        Document doc=new Document();
        doc.put("salary", 500);
        //这里使用了替换
        emp.replaceOne(eq, doc);//全部更新
        m.close();
    }

}

 

猜你喜欢

转载自www.cnblogs.com/hx1098/p/9375090.html