Mongodb

2021/06/16

Mongodb

参考资料

  • MongoDB中文社区:https://mongoing.com/
  • MongoDB中文网手册:https://mongodb.net.cn/manual/
  • MongoDB中文手册 官方文档中文版: https://docs.mongoing.com/
  • https://www.runoob.com/mongodb/mongodb-tutorial.html
  • https://www.runoob.com/mongodb/mongodb-java.html

一、mongodb 简介

mongodb 是什么

MongoDB:是一个数据库 ,高性能、无模式、文档性,目前nosql中最热门的数据库,开源产品,基于c++开发。是nosql数据库中功能最丰富,最像关系数据库的。

mongodb 的使用场景

mongodb 的相关概念类比理解

二、mongodb 安装

三、集成mongodb

3.1 mongodb-driver操作mongodb

mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动

//1.添加依赖
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.8.2</version>
</dependency>

//2.MongoTest
public class MongoTest {
    //数据库  
    private MongoDatabase db;
    //文档集合
    private MongoCollection<Document> doc;
    //连接客户端
    private MongoClient client;

    @Before
    public void init() {
        //连接客户端
        client = new MongoClient("127.0.0.1", 27017);
        //获取db
        db = client.getDatabase("demo");
        //获取集合
        doc = db.getCollection("user");
    }

    @Test
    public void insertDemo() {
        Document doc1 = new Document();
        doc1.append("name", "张飞");
        doc1.append("age", 20);
        Document doc2 = new Document();
        doc2.append("name", "关羽");
        doc2.append("age", 20);
        Document doc3 = new Document();
        doc3.append("name", "赵云");
        doc3.append("age", 20);
        doc3.append("sex", "男");
        doc.insertMany(Arrays.asList(doc1, doc2, doc3));
    }

    @Test
    public void testFind() {
        //Consumer接口专门用于处理查询出来的数据
        Consumer<Document> printCustomer = new Consumer<Document>() {
            @Override
            public void accept(Document document) {
                System.out.println(document.toJson());
                System.out.println("############结束###########");
            }
        };
        //查询name包括赵云或张飞
        //db.users.find({"$or":[{"name":"赵云"},{"name":"张飞"}]})
        Bson zhaoyun = Filters.eq("name", "赵云");
        Bson zhangfei = Filters.eq("name", "张飞");
        Bson or = Filters.or(Arrays.asList(zhaoyun, zhangfei));
        FindIterable<Document> find = doc.find(or);
        find.forEach(printCustomer);
        //查询名字包含云子的人
        //db.users.find({"name":{"$regex":".*云.*"}})
        String regexStr = ".*云.*";
        Bson regex = Filters.regex("name", regexStr);
        FindIterable<Document> find1 = doc.find(regex);
        find1.forEach(printCustomer);
    }

    @Test
    public void testUpdate() {
        //修改  //db.users.update({"name":"赵云"},{"$set":{"age":28}})
        Bson zhaoyun = Filters.eq("name", "赵云");
        Bson setAge = Updates.set("age", 28);
        doc.updateOne(zhaoyun, setAge);
    }

    @Test
    public void testDelete() {
        Bson eq = Filters.eq("name", "关羽");
        DeleteResult deleteResult = doc.deleteMany(eq);
        System.out.println(deleteResult);
    }
}

3.2 spring集成mongodb使用MongoTemplate

https://blog.csdn.net/zhouzhiwengang/article/details/53096080

//1.添加依赖
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>3.0.3.RELEASE</version>
</dependency> 

//2.添加配置
spring.data.mongodb.database=springdata
spring.data.mongodb.host=192.168.127.128
spring.data.mongodb.password=admin
spring.data.mongodb.username=admin
spring.data.mongodb.port=27017

# 或者
spring.data.mongodb.uri: mongodb://name:pass@localhost:27017/test
##spring.data.mongodb.uri: mongodb://name:pass@localhost:27017/test?authSource=admin&authMechanism=SCRAM-SHA-1

#多个 IP 集群可以采用以下配置:
spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database

//3.使用
@Autowired
private MongoTemplate mongoTemplate;
//查询
public String getPageDta(pageDto dto) {
        Query query = new Query();
        Criteria cri = new Criteria();
        //拼条件
        List<Criteria> conditions = new ArrayList<>();
        Criteria time = new Criteria(StringConst.ADD_TIME);
        if (!StringUtil.isEmpty(jo.getStartTime())) {
            time.gte(jo.getStartTime());
        }
        if (!StringUtil.isEmpty(jo.getEndTime())) {
            time.lte(jo.getEndTime());
        }
        conditions.add(time);
        if (!StringUtil.isEmpty(jo.getCompanyId())) {
            conditions.add(new Criteria("companyId").is(jo.getCompanyId()));
        }
        cri.andOperator(conditions.toArray(new Criteria[0]));
        query = Query.query(cri);
        /*//新增
        mongoTemplate.save(**entity, "detect_fail_log");
        //删除
        mongoTemplate.remove(**Object, "detect_fail_log");
        // 判断集合是否存在
        boolean exists = mongoTemplate.collectionExists(collectionName);
        // 创建集合
        mongoTemplate.createCollection(collectionName);
        // 添加索引 companyId:1,time:1索引
        DBObject indexOptions = new BasicDBObject();
        indexOptions.put("companyId", 1);
        indexOptions.put("time", 1);
        CompoundIndexDefinition indexDefinition = new CompoundIndexDefinition(indexOptions);
        mongoTemplate.indexOps(collectionName).ensureIndex(indexDefinition);*/
        //查询总数
        String collectionName = "detect_fail_log";
        long count = mongoTemplate.count(query, collectionName);
        //分页数据
        query.with(new PageRequest(dto.getPageNumber() - 1, dto.getPageSize()));
        query.with(new Sort(Sort.Direction.DESC, "addTime"));
        List<Map<String, Object>> ret = new ArrayList<>();
        mongoTemplate.executeQuery(query, collectionName, dbObject -> {
            Map<String, Object> m = dbObject.toMap();
            //处理某些字段转换
            //statService.convertFileUrl(m, "capFileUrl");
            ret.add(m);
        });
        //返回
        JSONObject pageObject = new JSONObject();
        pageObject.put(Constants.PAGE_ROWS, ret);
        pageObject.put(Constants.PAGE_TOTAL, count);
        return pageObject;
}

3.3 springboot集成mongodb操作MongoTemplate

http://www.ityouknow.com/springboot/2017/05/08/spring-boot-mongodb.html

//1.添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

// 2.配置
spring:
  data:
    mongodb:
      host: 192.168.25.128  #指定主机
      database: spitdb    #指定数据库
      port: 27017            #指定端口
      #多个 IP 集群可以采用以下配置:
#或者
uri: mongodb://127.0.0.1:27017/demo  # 用户密码设置不需要@
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test
#多数据源
spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database

//3.绑定实体类与mongodb中的那个集合(表)
@Document(collection = "user")  
public class User implements Serializable {
    @Id                    #  唯一主键
    private String _id;
    
}

//4. dao使用MongoTemplate
@Component
public class UserRepository {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建对象
     */
    @Override
    public void saveUser(User user) {
        mongoTemplate.save(user);
    }

    /**
     * 根据用户名查询对象
     */
    @Override
    public User findUserByUserName(String userName) {
        Query query=new Query(Criteria.where("userName").is(userName));
        User user =  mongoTemplate.findOne(query , User.class);
        return user;
    }

    /**
     * 更新对象
     */
    @Override
    public long updateUser(User user) {
        Query query=new Query(Criteria.where("id").is(user.getId()));
        Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
        //更新查询返回结果集的第一条
        UpdateResult result =mongoTemplate.updateFirst(query,update,User.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,UserEntity.class);
        if(result!=null) return result.getMatchedCount();
        else return 0;
    }

    /**
     * 删除对象
     */
    @Override
    public void deleteUserById(Long id) {
        Query query=new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,User.class);
    }
}

//5.验证
    @Autowired
    private UserRepository userDao;

    @Test
    public void testSaveUser() throws Exception {
        User user=new User();
        user.setId(2l);
        user.setUserName("小明1");
        user.setPassWord("fffooo123");
        userDao.saveUser(user);
    }

    @Test
    public void findUserByUserName(){
        User user= userDao.findUserByUserName("小明1");
        System.out.println("user is "+user);
    }

    @Test
    public void updateUser(){
        User user=new User();
        user.setId(2l);
        user.setUserName("天空");
        user.setPassWord("fffxxxx");
        userDao.updateUser(user);
    }

    @Test
    public void deleteUserById(){
        userDao.deleteUserById(1l);
    }

3.4 配置多数据源

http://www.ityouknow.com/springboot/2017/05/08/spring-boot-mongodb.html

四、安全机制

五、问题记录

Post Directory

扫码关注公众号:暂无公众号
发送 290992
即可立即永久解锁本站全部文章