你的位置:首页 > 数据库

[数据库]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查询(一)简单查询》内容就可以组合成我们想要的各种结果的查询条件了