spring-data-mongoDB 操作 elemMatch命令

被elemMatch命令纠结了一下午。mongoDB自己的java驱动写法写好了。但是spring-data-mongoDB一直写不对。。

mongoDB语法:

db.users.find({score:{$elemMatch:{$gt:90,$lt:100}}}, {score:1})

 mongoDB java-Driver

@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();
    }

输出为:

{ "_id" : { "$oid" : "5450e79182ce1953fb0adbd5"} , "score" : [ 88.0 , 99.0 , 100.0]}
{ "_id" : { "$oid" : "5450e7ae82ce1953fb0adbd6"} , "score" : [ 88.0 , 99.0]}
{ "_id" : { "$oid" : "5450eaf982ce1953fb0adbd8"} , "score" : [ 88.0 , 99.0]}

 spring-data-mongoDB

@Test
    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());
        }
    }

输出为:

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]]

相关推荐