天天看點

springdata-mongodb學習使用筆記

springdata-mongodb學習使用筆記

文章目錄

    • springdata-mongodb學習使用筆記
      • 1. 學習資料
      • 2. MongoDB資料庫安裝
        • 注:給MongoDB設定密碼
      • 3. MongoDB用戶端使用
      • 4. spring-data-mongodb的使用
        • 4.1 配置資訊
          • 4.1.1 aplication.properties中的配置為
        • 4.2 建立删除集合
        • 4.3 添加資料
        • 4.3 建立唯一索引
          • 4.3.1 唯一索引
          • 4.3.2 複合唯一索引
        • 4.4 使用@Query注解進行查詢
        • 4.6 使用方法來實作查詢
        • 4.5 使用Java類來實作查詢
        • 4.6 模糊查詢
        • 4.7 分頁查詢
        • 4.8 根據集合中的字段進行查詢

1. 學習資料

  • 入門級:MongoDB教程|菜鳥教程
  • 官方文檔:Spring Data MongoDB - Reference Documentation
  • 官方API:Spring Data MongoDB 2.1.10.RELEASE API

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伺服器相關資訊
springdata-mongodb學習使用筆記
第二步:配置資料庫名稱和資料庫賬号和密碼
springdata-mongodb學習使用筆記

4. spring-data-mongodb的使用

4.1 配置資訊

4.1.1 aplication.properties中的配置為
# mongodb資料庫配置 
 spring.data.mongodb.uri=mongodb://name:[email protected]: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

Keyword Sample Logical 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/