`
kesun_shy
  • 浏览: 485636 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

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

 

 

 

0
0
分享到:
评论
1 楼 daquan198163 2015-07-23  
http://www.mkyong.com/mongodb/spring-data-mongodb-query-document/
You can’t use Criteria.and() to add multiple criteria into the same field, to fix it, use Criteria.andOperator(), see updated example :

相关推荐

Global site tag (gtag.js) - Google Analytics