zoukankan      html  css  js  c++  java
  • 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查询(一)简单查询》内容就可以组合成我们想要的各种结果的查询条件了

  • 相关阅读:
    vim插件:显示树形目录插件NERDTree安装 和 使用【转】
    CMake 入门实战【转】
    在 linux 下使用 CMake 构建应用程序【转】
    Buildroot构建指南——根文件系统(Rootfs)【转】
    Buildroot构建指南--快速上手与实用技巧【转】
    Vim升华之树形目录插件NERDTree安装图解【转】
    【转】Android端与Android端利用WIFI进行FTP通信
    【转】Android 服务器之SFTP服务器上传下载功能 -- 不错
    【转】session setup failed: NT_STATUS_LOGON_FAILURE -- 不错
    【转】Mac OS X开机启动Path had bad permissions错误解决方案
  • 原文地址:https://www.cnblogs.com/luoaz/p/4692716.html
Copyright © 2011-2022 走看看