java MongoDB查询(二)复杂查询

前言

        在上篇《java MongoDB查询(一)简单查询》中我们简单了解了下查询,但是仅仅有那些查询是不够用的,还需要复杂的查询,这篇就这点进行叙述。

1、数据结构

        集合:firstCollection

        数据内容:

        { "_id" : ObjectId("55adba52fa1f3cf038c2aea6"), "name" : "user0", "age" : 22, "sex" : 0 }

        { "_id" : ObjectId("55adba52fa1f3cf038c2aea7"), "name" : "user1", "age" : 23, "sex" : 1 }

        { "_id" : ObjectId("55adba52fa1f3cf038c2aea8"), "name" : "user2", "age" : 24, "sex" : 0 }

        { "_id" : ObjectId("55adba52fa1f3cf038c2aea9"), "name" : "user3", "age" : 25, "sex" : 1 }

        { "_id" : ObjectId("55adba52fa1f3cf038c2aeaa"), "name" : "user4", "age" : 26, "sex" : 0 }

        { "_id" : ObjectId("55adba52fa1f3cf038c2aeab"), "name" : "user5", "age" : 27, "sex" : 1 }

2、连接数据库,拿到集合firstCollection

 

        MongoClient mClient = new MongoClient("10.211.55.8");

        DB db = mClient.getDB("test");

        DBCollection collection = db.getCollection("firstCollection");

3、与查询

        操作符:$and

        场景:查询age大于23,并且sex为1的对象

        查询条件Json内容:

        {"$and":[{"age":{"$gt":23}},{"sex":1}]}

        查询条件Java内容:

        BasicDBObject ageObj = new BasicDBObject("age",new BasicDBObject("$gt",23));

        BasicDBObject sexObj = new BasicDBObject("sex",1);

        BasicDBObject andObj = new BasicDBObject("$and",Arrays.asList(ageObj,sexObj));

        执行过程:

        Cursor cursor = collection.find(andObj);

        while(cursor.hasNext()){

                DBObject obj = cursor.next();

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

        }

4、或查询

        操作符:$or

        场景:查询name为user2,或者name为user3的对象

        查询条件Json内容:

        {"$or":[{"name":"user2"},{"name":"user3"}]}

        查询条件Java内容:

        BasicDBObject user2Obj = new BasicDBObject("name","user2");

        BasicDBObject user3Obj = new BasicDBObject("name","user3");

        BasicDBObject orObj = new BasicDBObject("$or",Arrays.asList(user2Obj,user3Obj));

        执行过程:

        Cursor cursor = collection.find(orObj);

        while(cursor.hasNext()){

                DBObject obj = cursor.next();

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

        }

5、总结

        通过与或的查询,我们了解了查询条件组合的方式,通过这种方式,再联系上篇《java MongoDB查询(一)简单查询》内容就可以组合成我们想要的各种结果的查询条件了

转载于:https://www.cnblogs.com/luoaz/p/4692716.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值