Spring data mongodb实现嵌套查询,并指定返回子集内容

mongo格式:

{
    "_id" : "1",
    "userId" : "2",
    "bookId" : "1",
    "historyList" : [ 
        {
            "_id" : "1",
            "hh" : "1"
        }, 
        {
            "_id" : "2",
            "hh" : "2"
        }, 
        {
            "_id" : "3",
            "hh" : "2"
        }
    ],
    "_class" : "com.domain.UseHistory"
}


正常的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);
        }

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值