MongoDB在SpringBoot中使用

1.引用

        <!-- mongo -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2.配置

####################mongodb##########################
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/earth

earth是db名,在创建db时还需要创建至少一个collection(类似table)

3.方法调用

@Component
public class MongoComponent {

    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    
    /**
     * 
     * @param brand
     */
    public void save(BrandEntity brand) {
        
        
        mongoTemplate.save(brand);        
    }
    
    
    /**
     * 
     * @param registerNum
     * @return
     */
    public BrandEntity findByRegisterNum(String registerNum) {
        
        Query q = new Query(Criteria.where("registerNum").is(registerNum));
    
        return mongoTemplate.findOne(q, BrandEntity.class);
    }
    
    
    /**
     * 
     * @param registerNum
     */
    public void deleteByRegisterNum(String registerNum) {
        
        Query q = new Query(Criteria.where("registerNum").is(registerNum));
                
        mongoTemplate.remove(q, BrandEntity.class);
    }
    
    
    /**************************Collection************************/
    
    
    /**
     * 
     * @param brand
     * @param collectionName
     */
    public void saveInCollection(BrandEntity brand, String collectionName) {
        
        
        mongoTemplate.save(brand, collectionName);
    }
        
    
    /**
     * 
     * @param registerNum
     */
    public void deleteByRegisterNumInCollection(String registerNum, String collectionName) {
        
        Query q = new Query(Criteria.where("registerNum").is(registerNum));
                
        mongoTemplate.remove(q, BrandEntity.class, collectionName);
    }
    
    /**
     * 
     * @param registerNum
     * @param collectionName
     * @return
     */
    public BrandEntity findOneByRegisterNumInCollection(String registerNum, String collectionName) {
        
        Query q = new Query(Criteria.where("registerNum").is(registerNum));
        
        return mongoTemplate.findOne(q, BrandEntity.class, collectionName);
    }
    
    
    /**
     * 
     * @param sTime
     * @param eTime
     * @param collectionName
     * @return
     */
    public List<BrandEntity> findByIntervalInCollection(Date sTime, Date eTime, String collectionName) {
        
        Query q = new Query(Criteria.where("updateTime").gte(sTime).lte(eTime));
        
        
        return mongoTemplate.find(q, BrandEntity.class, collectionName);
        
    }
}

 

上一篇:【转】《Pandas Cookbook》第05章 布尔索引


下一篇:mongodb-java常用语法-增删改查