mongotemplate范围查询_spring data mongo (Mongotemplate) 的高级常用查询

数组字段查询 elemMatch

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 = mongoTemplate.find(query, Users.class);

for(Users users2 : users) {

System.out.println(users2.toString());

}

}

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

结果:

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

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

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 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);

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值