spring data mongo (Mongotemplate) 的高级常用查询

目录

数组字段查询 elemMatch

嵌套元素查询  json格式

对数组元素进行追加,删除

数组元素去重追加一个或者多个值   $addToSet


1、查询数组元组  比如  每条记录都有  score:[23,45,20],想查询score 所有分数都大于多少分数,或者含有等于多少分的


@Test
    public void testFind3(){
        final BasicDBObject test = new BasicDBObject("score", new BasicDBObject("$elemMatch", new BasicDBObject("$gt", 90).append("$lt", 100)));
        final BasicDBObject keys = new BasicDBObject("score", 1);
        DBCursor cursor = getCollection().find(test, keys);
        while (cursor.hasNext()) {
            DBObject object = cursor.next();
            System.out.println(object);
        }
        cursor.close();
    }


public void testFind3() {
        Criteria cri = Criteria.where("$gt").is(90).and("$lt").is(100);
        Query query = new Query(Criteria.where("score").elemMatch(cri));
        query.fields().include("score");
        List<Users> users = mongoTemplate.find(query, Users.class);
        for(Users users2 : users) {
            System.out.println(users2.toString());
        }
    }



criteria.and("score").elemMatch(new Criteria("$eq").is(26));

结果:

  1. Users [id=5450e79182ce1953fb0adbd5, username=null, password=null, age=null, score=[88, 99, 100]]

  2. Users [id=5450e7ae82ce1953fb0adbd6, username=null, password=null, age=null, score=[88, 99]]

  3. Users [id=5450eaf982ce1953fb0adbd8, username=null, password=null, age=null, score=[88, 99]]

嵌套元素查询  json格式

有些字段如下

"historyList" : [ 
        {
            "_id" : "1",
            "hh" : "1"
        }, 
        {
            "_id" : "2",
            "hh" : "2"
        }, 
        {
            "_id" : "3",
            "hh" : "2"
        }
    ]
//正常的mongoTemplate写法
Query query = new Query();
query.addCriteria(Criteria.where("userId").is("2").and("historyList._id").is("1"));
System.out.println(query.toString());
return mongoTemplate.find(query,UseHistory.class);

//但是这种写法不能满足,会将符合查询要求的整行数据全部返回,包含所有的子集。

Aggregation写法
History history = null;
        //封装对象列表查询条件
        List<AggregationOperation> commonOperations = new ArrayList<>();
        //1. 指定查询主文档
        MatchOperation match = Aggregation.match(Criteria.where("userId").is("2"));
        commonOperations.add(match);
        //2. 指定投影,返回哪些字段
        ProjectionOperation project = Aggregation.project("historyList");
        commonOperations.add(project);
        //3. 拆分内嵌文档
        UnwindOperation unwind = Aggregation.unwind("historyList");
        commonOperations.add(unwind);
        //4. 指定查询子文档
        MatchOperation match2 = Aggregation.match(
                Criteria.where("historyList.hh").is("2"));
        commonOperations.add(match2);
 
        //创建管道查询对象
        Aggregation aggregation = Aggregation.newAggregation(commonOperations);
        AggregationResults<JSONObject> reminds = mongoTemplate
                .aggregate(aggregation, "history", JSONObject.class);
        List<JSONObject> mappedResults = reminds.getMappedResults();
        if (mappedResults != null && mappedResults.size() > 0) {
            history = JSONObject
                    .parseObject(mappedResults.get(0).getJSONObject("historyList").toJSONString(), History.class);
        }

对数组元素进行追加,删除

//纯数组删除其中元素
{
    "_id" : ObjectId("5b921e02d833f81e08fb674f"),
    ……
    "code" : [ 
        "6380500517",
        "6380500518",
        "6380500519"
    ]
}

db.表明.find(
{'code':'6380500517'}
)

db.表名.updateMany(
{'code':'6380500517'},
{'$pull': {'code':'6380500517'}}
)


//json格式数组删除其中一个元素

{
    "_id" : ObjectId("56e2a92ccc6dd2271953e502"),
    "links": [
        {
            "name": "Google",
            "url": "http://www.google.com"
        },
        {
            "name": "Baidu",
            "url": "http://www.baidu.com"
        },
        {
            "name": "SoSo",
            "url": "http://www.SoSo.com"
        }
    ]
}

//删除百度
db.collection.update(
  { _id: ObjectId('id') },
  { $pull: { links: { name: 'Baidu' } } }
);

...
criteria.and("id").is('xxx');//先定位到这一条
mongoQuery = new Query(criteria)
Update update = new Update();
update.pull("links",new BasicDBObject("name",'Baidu'));//从links中拉出符合条件的一条
mongoTemplate.updateMulti(mongoQuery, update, xx.class);
//数组追加

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"}}})


 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 "追加完成";
            }
        }



数组元素修改其中的一个jons值


{
    "_id": ObjectId("5550622dfc194b340a1feb5f"),
    "name": "hsaflkjhdf",
    "desc": "dfsafsdafsafad",
    "type": "微企模板",
    "template": [
        {
            "_id": ObjectId("5550d3280a706d025d8eb5d6"),
            "view": "aaaaaaaaaaa",
            "image": "http://127.0.0.1:7012/staticdata/newsdata/template/images/redare/5550622dfc194b340a1feb5f/143136029221214278739681.jpg"
        }
    ]
删除template子元素中的一条记录:

Update update = new Update();
update.pull("template",new BasicDBObject("id",templateId));
Query query = Query.query(Criteria.where("id").is(viewTemplateId));
return mongodbTemplate.updateFirst(query,update,ViewTemplate.class);
修改template子元素的某一条满足条件的记录:

 Query query = Query.query(new Criteria().andOperator(Criteria.where("companyName").is(riskvo.getCompanyName()),Criteria.where("risks").elemMatch(Criteria.where("riskPoint").is(riskvo.getRiskPoint()))));
            Update update = new Update();
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("riskPoint", riskvo.getRiskPoint());
//            jsonObject.put("source", 1);
//            jsonObject.put("riskDetail", riskvo.getRiskDetail());
//            jsonObject.put("type", riskvo.getType());

            update.set("risks.$.riskPoint", riskvo.getRiskPoint());
            update.set("risks.$.riskDetail", riskvo.getRiskDetail());
            update.set("risks.$.type", riskvo.getType());
            update.set("risks.$.source", 1);
            mongoTemplate.updateMulti(query, update, "machineAllocation");

数组元素去重追加一个或者多个值   $addToSet

添加值到一个数组中,如果该数组中已经存在该值,则不会添加;如果不存在该值,则添加

db.collcetion.update({"_id":"123"}, {"$addToSet":{"likes":"PingPang"}})
如果想要批量添加list,需要配合$each使用

db.collcetion.update({"_id":"123"}, {"$addToSet":{"likes":{"$each":["PingPang","FootBall","BasketBall"]}}})


//去重添加一个值
Query query = new Query(Criteria.where("_id").is(123))
 Document updateDoc = new Document();
 updateDoc.append("$addToSet", new Document().append("listKey", gameId));
 BasicUpdate update = new BasicUpdate(updateDoc);
 // 实现数据存在就更新,不存在就插入数据
 mongoTemplate.upsert(query, update, docName);

//去重添加多个值

/**
 * 批量更新用户信息组信息
 * @param userIds
 * @param groupIDs
 */
public void batchUpdateUser(Object[] userIds,Object[] groupIDs) {
    Criteria c = Criteria.where("_id").in(userIds);
    Update update = new Update();
    Update.AddToSetBuilder ab = update.new AddToSetBuilder("groupIDs");
    update = ab.each(groupIDs);
    mongoTemplate.updateMulti(new Query(c),update,SystemContent.COLLECTION_NAME_APPLYUSER);
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Data MongoDB是一个用于与MongoDB数据库进行交互的框架。它提供了一个简化和高效的方式来访问和操作MongoDB数据库,并使开发人员能够更容易地使用Spring框架来开发MongoDB应用程序。 Spring Data MongoDB的核心组件是MongoTemplate,它是一个线程安全的MongoDB操作模板类。通过MongoTemplate,我们可以进行诸如查询、插入、更新和删除等常见的数据库操作。 使用MongoTemplate,我们可以使用MongoDB的查询语言来进行数据库查询。通过构建一个查询对象,我们可以指定要查询的集合、查询的条件和排序等。除了基本的查询外,MongoTemplate还提供了一些更高级查询方法,如聚合查询、分页查询和地理位置查询等。 对于插入、更新和删除操作,MongoTemplate提供了各种方法来执行这些操作。我们可以使用save()方法来插入或更新一个文档,使用delete()方法来删除一个或多个文档,并使用update()方法来更新一个或多个文档的值。 除了基本的操作外,MongoTemplate还提供了一些其他功能,如文档映射、索引管理和事务支持等。我们可以通过配置注解来定义文档和集合之间的映射关系,通过索引注解来定义索引,以提高查询性能。此外,Spring Data MongoDB还提供了对事务管理的支持,以确保在多个操作之间的一致性。 总之,Spring Data MongoDB是一个强大而灵活的框架,它为开发人员提供了一套简化和高效的API,用于与MongoDB数据库进行交互。通过MongoTemplate,我们可以轻松地进行查询、插入、更新和删除等常见的数据库操作,并享受到Spring框架的许多好处。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值