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 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 reminds = mongoTemplate
                    .aggregate(aggregation, "history", JSONObject.class);
            List mappedResults = reminds.getMappedResults();
            if (mappedResults != null && mappedResults.size() > 0) {
                history = JSONObject
                        .parseObject(mappedResults.get(0).getJSONObject("historyList").toJSONString(), History.class);
            }

你可能感兴趣的:(mongo,springboot,spring,mongo,嵌套查询)