MongoDB-Java MongoDB MongoTemplate 查询

MongoTemplate帮助器类,可提高执行常见Mongo操作的效率。包括文档和POJO之间的集成对象映射。
相对于MongoRepository的操作MongoTemplate的操作更多也更灵活。
MongoTemplate可以对collection进行操作;而且通过Query和criteria的结合我们可以以一种比较“面向对象”的方式完成各种查询和更新操作。

注意

MongoDB在使用Template查询的时候注意要查询的字段类型和传参保持一致,如果类型不一致不会抛异常而是查不出结果;这个大家使用的时候要注意。

“123” != 123

然后在写更新语句的时候写入类型要指定

new Date("2020-11-29 04:33:38.000"), "speaker" :new NumberLong( "4891554746090405888")
db.getCollection("DemoCollection").update({ "drId" :new NumberLong(" 4909159988835622912")} , { $push : { "contexts" : { "time" :new Date("2020-11-29 04:33:38.000"), "speaker" :new NumberLong( "4891554746090405888"), "context" : "MongoTemplate 并列条件查询和数组字段追加操作", "_class" : "xxx.xxx.xxx.pojo.po.Context"}}})

MongoTemplate 时间段查询

lt:小于 lte: 小于等于 gte :大于等于 gt: 大于

lte less than equal

gte greater than equal

 // xxx时间大于等于开始时间
 if (caseListBO.getReceiveBeginTime() != null) {
     criteria.and("xxxTime").gte(caseListBO.getBeginTime());
 }

 // xxx时间小于等于结束时间
 if (caseListBO.getReceiveEndTime() != null) {
     criteria.and("xxxTime").lte(caseListBO.getEndTime());
 }

MongoTemplate 多种情景模糊查询

按照姓名精确查询

Query query = new Query();
query.addCriteria(Criteria.where("name").is(name));

按照姓名模糊查询

Pattern pattern=Pattern.compile("^.*"+pattern_name+".*$", Pattern.CASE_INSENSITIVE);
query.addCriteria(Criteria.where("name").regex(pattern))

多条件查询

Query query = new Query();
query.addCriteria(Criteria.where("name").is(name));
query.addCriteria(Criteria.where("age").is(age));

或者另外一种写法

Criteria criteria = new Criteria();
criteria.and("name").is(name);
criteria.and("_id").is(new ObjectId(id));
Query query = new Query(criteria);

一个模糊关键字匹配多字段

 Pattern pattern=Pattern.compile("^.*"+pattern_name+".*$", Pattern.CASE_INSENSITIVE);
            criatira.orOperator(Criteria.where("name").regex(pattern),
                    Criteria.where("sex").regex(pattern),
                    Criteria.where("age").regex(pattern),
                    Criteria.where("class").regex(pattern));

并列查询

同时 and + or 查询

        Query query = new Query();

        query.addCriteria(new Criteria().andOperator(
                Criteria.where("drId").is(dialogRecordId)
                .orOperator(
                        Criteria.where("to").is(userId) ,
                        Criteria.where("from").is(userId))
                )
        );

        Long matchCount = mongoTemplate.count(query, "DemoCollection");
        if (matchCount == 1) {
            return "find one");
        }

db.getCollection("DemoCollection").find({ $and : [{"drId" : 4909159988835622912}, { $or : [{"from" : 4891554746090405888}, {"to" : 4891554746090405888}] }] })

数组字段的追加操作

    Context msg = new Context();
    msg.setSpeaker(baseUserInfo.getUserId());
    msg.setTime(new Date());
    msg.setContext(context);

    Query query = new Query();
    query.addCriteria(Criteria.where("drId").is(dialogRecordId));
    Update update = new Update();
    update.push("contexts", msg);

    UpdateResult updateResult = mongoTemplate.updateFirst(query, update, "DemoCollection");
    if (updateResult.getMatchedCount() == 1) {
        if (updateResult.getModifiedCount() >= 1) {
            return "追加完成";
        }
    }

映射的语句

Calling update using query: { "drId" : 4909159988835622912} and update: { "$push" : { "contexts" : { "time" : { "$date" : "2020-11-29T04:33:38.277Z"}, "speaker" : 4891554746090405888, "context" : "今天午饭吃什么", "_class" : "xxx.xxx.xxx.pojo.po.Context"}}} in collection: DemoCollection

MongoDB语法:

db.getCollection("DemoCollection").update({ "drId" :new NumberLong(" 4909159988835622912")} , { $push : { "contexts" : { "time" :new Date("2020-11-29 04:33:38.000"), "speaker" :new NumberLong( "4891554746090405888"), "context" : "MongoTemplate 并列条件查询和数组字段追加操作", "_class" : "xxx.xxx.xxx.pojo.po.Context"}}})

查询字段不存在的数据

public List<GoodsDetail> getGoodsDetails2(int begin, int end) {  
        Query query = new Query();  
        query.addCriteria(Criteria.where("goodsSummary").not());  
        return find(query.limit(end - begin).skip(begin),GoodsDetail.class);  
    }  

查询字段不为空的数据,字段不等于某个值

Criteria.where("key1").ne("").ne(null)  

查询或语句:a || b

Criteria criteria = new Criteria();  
criteria.orOperator(Criteria.where("key1").is("0"),Criteria.where("key1").is(null));  

MongoTemplate如何返回指定字段

    /**
     * @param id     id
     * @param fields 要查询的字段
     * @return
     */
    public InfoSupplementEntity findTest(String id, List<String> fields) {
        Query query = new Query(Criteria.where("id").is(id));
        Field findFields = query.fields();
 
        if (!CollectionUtils.isEmpty(fields)) {
            fields.forEach(findFields::include);
        }
        return mongoTemplate.findOne(query, InfoSupplementEntity.class);
 
    }

1.第一种:

Query query=new Query();
query.addfields().include("你要返回的字段1");
query.addfields().include("你要返回的字段2");
query.addfields().exclude("你不返回的字段");
query.addCriteria(Criteria.where("XM").ne(null));//你要添加的查询
return mongoTemplate.find(query,你要返回的类型.class);

2.第二种:

注释方法

@Query(value="{'_id':>0}",fields="{'name':1}")
User findNameById(Object id);

待测试

参考

MongoTemplate 并列条件查询和数组字段追加操作
https://blog.csdn.net/wangxudongx/article/details/110307735

Mongotemplate多种情景模糊查询
https://blog.csdn.net/weixin_42227975/article/details/80533678

MongoTemplate如何返回指定字段

https://blog.csdn.net/m0_37648645/article/details/103586653?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link

JAVA MONGODB 查询时间段
https://blog.csdn.net/edc0228/article/details/92645396

MongoTemplate针对多条件查询以及复杂查询基本示例

https://blog.csdn.net/Kiss_The_sky/article/details/78166812?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link

你可能感兴趣的:(mongodb,java)