springdata-mongodb学习使用笔记

springdata-mongodb学习使用笔记

1. 学习资料

2. MongoDB数据库安装

参考地址: https://www.runoob.com/mongodb/mongodb-window-install.html

注:给MongoDB设置密码

参见:给你的mongodb设置密码吧!

3. MongoDB客户端使用

本人使用的客户端连接工具为studio 3T,官方地址:https://studio3t.com/
CSDN下载地址(非最新):https://download.csdn.net/download/simadi/11339530

连接MongoDB步骤

第一步:配置MongoDB服务器相关信息
在这里插入图片描述
第二步:配置数据库名称和数据库账号和密码
在这里插入图片描述

4. spring-data-mongodb的使用

4.1 配置信息
4.1.1 aplication.properties中的配置为
 # mongodb数据库配置 
 spring.data.mongodb.uri=mongodb://name:password@localhost:27017/databaseName 
4.2 创建删除集合
    // 注入MongoTemplate进行相关的操作
    @Resource
    private MongoTemplate mongoTemplate;

    public void mongdbTest(){
        mongoTemplate.createCollection("collectionName");
        System.out.println("创建一个集合");
        mongoTemplate.dropCollection("collectionName");
        System.out.println("删除一个集合");
    }

此外在MongoDB中可以无需创建集合,直接插入文档,MongoDB能自动创建集合。
mongoTemplate.insert(exampleList, "collectionName");

4.3 添加数据

mongoTemplate.insert(exampleList, "collectionName");

4.3 创建唯一索引
4.3.1 唯一索引

参考:SpringBoot中MongoDB注解概念及使用
加载字段声明上:@Indexed(unique = true)

4.3.2 复合唯一索引

加在类声明上:

@CompoundIndexes({ 
    // 唯一复合索引:楼层和房号不能相同,不然就是同一个房间了
    @CompoundIndex(name = "floor_num", def = "{'floor' : 1, 'num': 1}",unique=true) 
})

参考地址:https://www.cnblogs.com/linzhanfly/p/9760821.html

4.4 使用@Query注解进行查询

1. 创建dao接口集成MongoRepository
2. 写方法,在方法上加@Query注解,在@Query()括号内写上JSON格式的条件,其中有value,sort等属性,需要注意的时,目前我只发现value中的查询条件只能写一个,多了会报com.mongodb.util.JSONParseException,因此对应多条件复杂查询还是使用Java类实现比较好
如:

public interface MmxDao extends MongoRepository<Mmx,String> {
    /**
     * 根据编号和时间段来查找
     * @param bh 编号
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 返回查询结果集
     */
    @Query("{'lxsj':{$gt:?1,$lt:?2}}")
    List<Mmx> findByBhAndTime(String bh, Date startTime,Date endTime);

 }
4.6 使用方法来实现查询

springData MongoDB中支持的使用方法名查找的方法如,不过需要继承相应的Repository,
具体的请看官方文档

Table 7. Supported keywords for query methods
KeywordSampleLogical result

After

findByBirthdateAfter(Date date)

{"birthdate" : {"$gt" : date}}

GreaterThan

findByAgeGreaterThan(int age)

{"age" : {"$gt" : age}}

GreaterThanEqual

findByAgeGreaterThanEqual(int age)

{"age" : {"$gte" : age}}

Before

findByBirthdateBefore(Date date)

{"birthdate" : {"$lt" : date}}

LessThan

findByAgeLessThan(int age)

{"age" : {"$lt" : age}}

LessThanEqual

findByAgeLessThanEqual(int age)

{"age" : {"$lte" : age}}

Between

findByAgeBetween(int from, int to)

{"age" : {"$gt" : from, "$lt" : to}}

In

findByAgeIn(Collection ages)

{"age" : {"$in" : [ages…​]}}

NotIn

findByAgeNotIn(Collection ages)

{"age" : {"$nin" : [ages…​]}}

IsNotNull, NotNull

findByFirstnameNotNull()

{"firstname" : {"$ne" : null}}

IsNull, Null

findByFirstnameNull()

{"firstname" : null}

Like, StartingWith, EndingWith

findByFirstnameLike(String name)

{"firstname" : name} (name as regex)

NotLike, IsNotLike

findByFirstnameNotLike(String name)

{"firstname" : { "$not" : name }} (name as regex)

Containing on String

findByFirstnameContaining(String name)

{"firstname" : name} (name as regex)

NotContaining on String

findByFirstnameNotContaining(String name)

{"firstname" : { "$not" : name}} (name as regex)

Containing on Collection

findByAddressesContaining(Address address)

{"addresses" : { "$in" : address}}

NotContaining on Collection

findByAddressesNotContaining(Address address)

{"addresses" : { "$not" : { "$in" : address}}}

Regex

findByFirstnameRegex(String firstname)

{"firstname" : {"$regex" : firstname }}

(No keyword)

findByFirstname(String name)

{"firstname" : name}

Not

findByFirstnameNot(String name)

{"firstname" : {"$ne" : name}}

Near

findByLocationNear(Point point)

{"location" : {"$near" : [x,y]}}

Near

findByLocationNear(Point point, Distance max)

{"location" : {"$near" : [x,y], "$maxDistance" : max}}

Near

findByLocationNear(Point point, Distance min, Distance max)

{"location" : {"$near" : [x,y], "$minDistance" : min, "$maxDistance" : max}}

Within

findByLocationWithin(Circle circle)

{"location" : {"$geoWithin" : {"$center" : [ [x, y], distance]}}}

Within

findByLocationWithin(Box box)

{"location" : {"$geoWithin" : {"$box" : [ [x1, y1], x2, y2]}}}

IsTrue, True

findByActiveIsTrue()

{"active" : true}

IsFalse, False

findByActiveIsFalse()

{"active" : false}

Exists

findByLocationExists(boolean exists)

{"location" : {"$exists" : exists }}

4.5 使用Java类来实现查询

参考地址:https://blog.csdn.net/abc466038366/article/details/83780614

Sort sort = new Sort(Sort.Direction.ASC, “DEVID”).and(new Sort(Sort.Direction.ASC, “TIME”));//多条件DEVID、time
Criteria criteria = Criteria.where(“CHECK”).is(0);//查询条件
Query query = new Query(criteria);
mongoTemplate.find(query.with(sort).limit(1000), UnormalInfo.class);

使用Java类实现复杂的查询

4.6 模糊查询

参考地址:https://blog.csdn.net/u011555260/article/details/82260441
https://blog.csdn.net/wd521521/article/details/82801192
根据姓名和学号模糊查找学生,最多查找6人

public List<StudentSearch> fuzzySearch(String content) {
        Pattern patternName=Pattern.compile("^.*"+content+".*$", Pattern.CASE_INSENSITIVE);
        Pattern patternNo=Pattern.compile("^.*"+content+".*$", Pattern.CASE_INSENSITIVE);
        Criteria criteria=new Criteria().orOperator(
          Criteria.where("name").regex(patternName),
          Criteria.where("no").regex(patternNo)
        );
        Query query=new Query(criteria);
        return mongoTemplate.find(query.limit(6),StudentSearch.class);
    }

关于模糊查询的优化

4.7 分页查询

参考地址:https://www.cnblogs.com/jycboy/p/8969035.html

    @Resource
    private MongoTemplate mongoTemplate;
    @Override
    public Page<Example> findByBhAndPage(String bh, int pageIndex, int pageSize) {
        // 分页信息
        Pageable pageable=PageRequest.of(pageIndex,pageSize);
        // 排序
        Sort sort=new Sort(Sort.Direction.DESC,"bh");
        // 查询条件
        Criteria criteria=Criteria.where("bh").is(bh);
        Query query=new Query(criteria);
        // 使用MongoTemplate进行查询,然后使用PageableExecutionUtils.getPage()对查询结果进行包装,将分页信息包含进去
        return PageableExecutionUtils.getPage(mongoTemplate.find(query.with(sort).with(pageable), Example.class),
                pageable, () -> 0);
    }

注:pageIndex从0开始

4.8 根据集合中的字段进行查询

参考地址:https://blog.csdn.net/gao36951/article/details/41074191/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值