當(dāng)前位置:首頁(yè) > IT技術(shù) > 數(shù)據(jù)庫(kù) > 正文

SpringBoot 中 MongoDB 的簡(jiǎn)單使用
2021-09-09 09:55:31

一、SpringBoot 中 MongoDB 的簡(jiǎn)單使用

(1)pom 依賴(lài)
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
(2)yml配置
spring:
  data:
    mongodb:
      uri: mongodb://ydt:ydtnb@123.123.123.123:27017/ydt?authSource=ydt
(3)代碼
@Resource
private MongoTemplate mongoTemplate;

/**
 * 新增數(shù)據(jù)示例,jl_gps 集合沒(méi)有會(huì)自動(dòng)創(chuàng)建
 */
public void testSave() {
    BJlGps jlGps = new BJlGps();
    ...
    mongoTemplate.save(x, "jl_gps")
}

/**
 * 查詢(xún)數(shù)據(jù)示例
 */
public void testQuery() {
    List<TestEntity> list = new ArrayList();
    
    Query query = new Query();
    Criteria criteria = new Criteria();
    
    String dwid = getDwid();
    
    // 模糊查詢(xún)
    criteria.where("dwid").regex("^.*" + dwid + ".*$");
    /* 精確查詢(xún) */
    if (StringUtil.isNotEmpty(type)) {
        criteria.and("type").is(type);
    }
    /* 范圍查詢(xún) */
    if (StringUtil.isNotEmpty(sDate) && StringUtil.isNotEmpty(eDate)) {
        criteria.and("dt")
            .gte(DateUtil.strToDateLong(sDate))
            .lt(DateUtil.strToDateLong(eDate));
    }
    query.addCriteria(criteria);
    
    // 執(zhí)行查詢(xún),反饋結(jié)果集
    list = mongoTemplate.find(query, TestEntity.class, "test");
}

二、問(wèn)題補(bǔ)充(問(wèn)題提出者:王)

問(wèn)題一:使用 MongoTemplate 查詢(xún)數(shù)據(jù)第一次會(huì)比較慢

原因:第一次查詢(xún)會(huì)先建立連接,導(dǎo)致查詢(xún)慢
解決方案:在項(xiàng)目啟動(dòng)時(shí)建立連接
@Component
public class MongoConnTask implements ApplicationRunner {
    /**
     * Springboot啟動(dòng)時(shí),注入 MongoTemplate ,即可創(chuàng)建連接
     */
    @Resource
    private MongoTemplate mongoTemplate;
    
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        
    }
}

問(wèn)題二:可視化工具中查看時(shí)間相關(guān)數(shù)據(jù),發(fā)現(xiàn)與存進(jìn)去的時(shí)間少 8 小時(shí)

原因:MongoDB 存儲(chǔ)時(shí)間為標(biāo)準(zhǔn)時(shí)間,UTC +0:00。中國(guó)標(biāo)準(zhǔn)時(shí)間為 UTC +8:00。
解決方案:無(wú)需解決

MongoTemplate 在取數(shù)據(jù)時(shí),會(huì)自動(dòng)加 8H,保證存取一致。

本文摘自 :https://www.cnblogs.com/

開(kāi)通會(huì)員,享受整站包年服務(wù)立即開(kāi)通 >