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]]
相关推荐
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09
jaylong 2020-08-19
大秦铁骑 2020-08-19
thatway 2020-08-19