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

MongoDB的特点

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

安装和使用

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

mongod --dbpath F:mongodbdata --logpath F:mongodblogsa.log
启动mongo客户端:mongo


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

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

  • 执行创建MongoDB服务命令

    mongod --dbpath F:mongodbdata --logpath F:mongodblogsa.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();
    }

}

 上面介绍的值是简单的java对MongoDB的访问,下面介绍一下基于在Spring中如何配置MongDBTemplate

  1. 引入spring-data-mongo包
  2. 在applicationContext.xml添加spring配置信息

    • XML标签引入

      <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
        xsi:schemaLocation=
        "http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo-1.3.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    • MongoTemplate定义

      <mongo:db-factory id="mongoFactory" host="localhost" 
          port="27017" dbname="java20"/>
      
      <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
          <constructor-arg index="0" ref="mongoFactory">
          </constructor-arg>
      </bean>c
  3. 注入mongoTemplate对象使用

    //加载spring环境
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
    public class TestMOngoFactory {
        @Autowired // 自动装配组件
        public MongoTemplate temp;
    
        // 插入一个对象
        @Test
        public void test1() {
            DeptBean dept = new DeptBean(3, "赵四", "北京");
            temp.insert(dept);
        }
    
        // 查找全部数据
        @Test
        public void test2() {
            List<DeptBean> list = temp.findAll(DeptBean.class);
            for (DeptBean de : list) {
                System.out.println(de.toString());
            }
        }
    
        // 查找条件查找deptNo小于10的数据
        @Test
        public void test3() {
            Query query = new Query(Criteria.where("deptno").lt(10));
            List<DeptBean> find = temp.find(query, DeptBean.class);
            for (DeptBean d : find) {
                System.out.println(d.toString());
            }
        }
    
        // 更新一条数据
        @Test
        public void test4(){
            Query query=new Query(Criteria.where("deptno").is(1));//条件,相当于 where deptNO = 1
            Update update = new Update();
            update.set("dname", "王五");
            temp.updateFirst(query, update, DeptBean.class);
        }
        //按系统自动生成的id进行查询ID
        @Test
        public void test5(){
            DeptBean findById = temp.findById("5b5a84090dd5473d983978a9", DeptBean.class);
            System.out.println(findById.toString());
        }
        //添加时设置id
        @Test
        public void Test(){
            Book book = new Book();
            book.setId(1);
            book.setName("Java入门");
            mongo.insert(book);
        }
        
    
    }

    以上就是使用MongoDBTemplate进行对数据库进行简单的操作

原文地址:https://www.cnblogs.com/hx1098/p/9375090.html