mongodb第一次操作记录

spring boot项目中集成mongodb

 

application.xml配置

 data:
    mongodb:
      host: 192.168.1.166
      port: 27017
      password: lydsj@2019
      database: aaa
      username: root
      authentication-database: admin//给aaa数据库权限

如果database配置的是admin就不需要配置authentication属性

 上图配置如果没有authentication属性回报下面错误

Exception authenticating MongoCredential{mechanism=null, userName='ceshi', source='sms', password=, mechanismProperties={}}

导入maven jar 


            org.springframework.boot
            spring-boot-starter-data-mongodb
            2.1.8.RELEASE
        

注入bean

 @Resource
    private MongoTemplate mongoTemplate;

 

实现层逻辑

 MongoDbFactory mongoDbFactory = mongoTemplate.getMongoDbFactory();
            MongoDatabase db = mongoDbFactory.getDb();
            MongoCollection mongoCollection = db.getCollection(smsId);
            Document document = new Document("PHONE","11111111111")
                    .append("SEND_TIME", "15398054185")
                    .append("EXPIRE_DAY", "1")
                    .append("STATUS", "0")
                    .append("EXCLUDE_STATUS", "1");

            // 插入数据
            mongoCollection.insertOne(document);

            // 插入列表数据
            List list = new ArrayList<>();
            for(int i = 0;  i < 5;  i++){
                list.add( new Document("number", i).append("name","王某某"));
            }
            mongoCollection.insertMany(list);


            //查询多个
            Bson filter = Filters.in("PHONE",byId.getMessagePhoneList().split(","));
            //删除多个
            mongoCollection.deleteMany(filter);

            //查询多个
            Bson filter1 = Filters.eq("PHONE","15769696969");
            //删除一个
            mongoCollection.deleteOne(filter);

 

你可能感兴趣的:(mongodb)