码迷,mamicode.com
首页 > 数据库 > 详细

Java实现对MongoDB的AND、OR和IN操作 ,大于、小于等判断

时间:2014-09-17 17:00:53      阅读:371      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   os   使用   java   ar   strong   for   

本文转自http://blog.csdn.net/mydeman/article/details/6652387

在MongoDB的官方文档中关于Java操作的介绍,只给出了很简单的几个例子。这些例子虽然可以满足一定的需求,但是还并不是太完全。下面是我根据网页中的提示写的几个例子。

1.背景。用JUnit4.8.2实现的单元测试的形式。测试数据:

[plain] view plaincopyprint?

  1. {uid:10,username:"Jim",age:23,agender:"male"}

  2. {uid:27,username:"tom",age:13,agender:"male"}

  3. {uid:12,username:"Jane",age:31,agender:"female"}

  4. {uid:23,username:"Alex",age:47,agender:"male"}

  5. {uid:109,username:"Lily",age:24,agender:"female"}

{uid:10,username:"Jim",age:23,agender:"male"}
{uid:27,username:"tom",age:13,agender:"male"}
{uid:12,username:"Jane",age:31,agender:"female"}
{uid:23,username:"Alex",age:47,agender:"male"}
{uid:109,username:"Lily",age:24,agender:"female"}


单元测试的初始化和清理工作,主要是建立数据库连接、写入测试数据、清理测试数据:

[java] view plaincopyprint?

  1. private static List<BasicDBObject> documents = new ArrayList<BasicDBObject>();

  2. private static DBCollection coll;

  3. @BeforeClass

  4. public static void init(){

  5. try {

  6. initConnection();

  7. loadData();

  8. } catch (Exception e) {

  9. e.printStackTrace();

  10. }

  11. }

  12. private static void initConnection() throws UnknownHostException, MongoException{

  13. //Create a connection to Collection ‘user‘

  14. Mongo mongo = new Mongo("localhost", 27017);

  15. DB db = mongo.getDB("test");

  16. coll = db.getCollection("user");

  17. }

  18. private static void loadData() throws Exception{

  19. BufferedReader br = new BufferedReader(new InputStreamReader(MongoTest.class.getResourceAsStream("data")));

  20. String line = null;

  21. while((line = br.readLine()) != null){

  22. JSONObject jo = new JSONObject(line);

  23. //Convert JSONObject into BasicDBObject

  24. BasicDBObject dbObject = new BasicDBObject();

  25. Iterator<String> joKeys = jo.keys();

  26. while(joKeys.hasNext()){

  27. String key = joKeys.next();

  28. dbObject.put(key, jo.get(key));

  29. }

  30. documents.add(dbObject);

  31. }

  32. }

  33. @Before

  34. public void setUp(){

  35. //Insert all data into MongoDB

  36. for(BasicDBObject bdo : documents){

  37. coll.insert(bdo);

  38. }

  39. }

  40. @After

  41. public void cleanUp(){

  42. //Drop the collection to remove all data.

  43. //Note: it‘s not recommended.

  44. coll.drop();

  45. }

  private static List<BasicDBObject> documents = new ArrayList<BasicDBObject>();
        private static DBCollection coll;
        
        @BeforeClass
        public static void init(){
                try {
                        
                        initConnection();
                        
                        loadData();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
        
        private static void initConnection() throws UnknownHostException, MongoException{
                //Create a connection to Collection ‘user‘
                Mongo mongo = new Mongo("localhost", 27017);
                DB db = mongo.getDB("test");
                coll = db.getCollection("user");
        }
        
        private static void loadData() throws Exception{
                BufferedReader br = new BufferedReader(new InputStreamReader(MongoTest.class.getResourceAsStream("data")));
                String line = null;
                while((line = br.readLine()) != null){
                        JSONObject jo = new JSONObject(line);
                        
                        //Convert JSONObject into BasicDBObject
                        BasicDBObject dbObject = new BasicDBObject();
                        Iterator<String> joKeys = jo.keys();
                        while(joKeys.hasNext()){
                                String key = joKeys.next();
                                dbObject.put(key, jo.get(key));
                        }
                        
                        documents.add(dbObject);
                }
        }
        
        @Before
        public void setUp(){
                //Insert all data into MongoDB
                for(BasicDBObject bdo : documents){
                        coll.insert(bdo);
                }
        }
        
        @After
        public void cleanUp(){
                //Drop the collection to remove all data.
                //Note: it‘s not recommended.
                coll.drop();
        }


2. AND是比较简单的。

[java] view plaincopyprint?

  1. @Test

  2. public void testAnd(){

  3. //agender=‘female‘ AND age > 27

  4. DBObject queryCondition = new BasicDBObject();

  5. queryCondition.put("agender", "female");

  6. queryCondition.put("age", new BasicDBObject("$gt", 27));

  7. DBCursor dbCursor = coll.find(queryCondition);

  8. assertEquals(1, dbCursor.size());

  9. assertEquals("Jane", dbCursor.next().get("username"));

  10. }

  @Test
        public void testAnd(){
                //agender=‘female‘ AND age > 27      
                DBObject queryCondition = new BasicDBObject();
                queryCondition.put("agender", "female");
                queryCondition.put("age", new BasicDBObject("$gt", 27));
                DBCursor dbCursor = coll.find(queryCondition);
                assertEquals(1, dbCursor.size());
                assertEquals("Jane", dbCursor.next().get("username"));
        }


3.单个字段的OR操作。

[java] view plaincopyprint?

  1. @Test

  2. public void testOrSingleField(){

  3. DBObject queryCondition = new BasicDBObject();

  4. //age<15 OR age>27

  5. queryCondition = new BasicDBObject();

  6. BasicDBList values = new BasicDBList();

  7. values.add(new BasicDBObject("age", new BasicDBObject("$gt", 27)));

  8. values.add(new BasicDBObject("age", new BasicDBObject("$lt", 15)));

  9. queryCondition.put("$or", values);

  10. DBCursor dbCursor = coll.find(queryCondition);

  11. assertEquals(3, dbCursor.size());

  12. assertEquals("tom", dbCursor.next().get("username"));

  13. }

  @Test
        public void testOrSingleField(){
                DBObject queryCondition = new BasicDBObject();          
                //age<15 OR age>27
                queryCondition = new BasicDBObject();
                BasicDBList values = new BasicDBList();
                values.add(new BasicDBObject("age", new BasicDBObject("$gt", 27)));
                values.add(new BasicDBObject("age", new BasicDBObject("$lt", 15)));
                queryCondition.put("$or", values);
                
                DBCursor dbCursor = coll.find(queryCondition);
                assertEquals(3, dbCursor.size());
                assertEquals("tom", dbCursor.next().get("username"));
        }


4. 多个字段之间的OR操作

[java] view plaincopyprint?

  1. @Test

  2. public void testOrMultiFields(){

  3. DBObject queryCondition = new BasicDBObject();

  4. //agender=female OR age<=23

  5. queryCondition = new BasicDBObject();

  6. BasicDBList values = new BasicDBList();

  7. values.add(new BasicDBObject("agender", "female"));

  8. values.add(new BasicDBObject("age", new BasicDBObject("$lte", 23)));

  9. queryCondition.put("$or", values);

  10. DBCursor dbCursor = coll.find(queryCondition);

  11. assertEquals(4, dbCursor.size());

  12. assertEquals("Jim", dbCursor.next().get("username"));

  13. }

  @Test
        public void testOrMultiFields(){
                DBObject queryCondition = new BasicDBObject();          
                //agender=female OR age<=23
                queryCondition = new BasicDBObject();
                BasicDBList values = new BasicDBList();
                values.add(new BasicDBObject("agender", "female"));
                values.add(new BasicDBObject("age", new BasicDBObject("$lte", 23)));
                queryCondition.put("$or", values);
                
                DBCursor dbCursor = coll.find(queryCondition);
                assertEquals(4, dbCursor.size());
                assertEquals("Jim", dbCursor.next().get("username"));
        }


5. 单个字段的IN操作。对于类似 where age=13 OR age=47的查询条件,就可以考虑使用IN代替

[java] view plaincopyprint?

  1. @Test

  2. public void testIn(){

  3. DBObject queryCondition = new BasicDBObject();

  4. //age in [13, 47]

  5. queryCondition = new BasicDBObject();

  6. BasicDBList values = new BasicDBList();

  7. values.add(13);

  8. values.add(47);

  9. queryCondition.put("age", new BasicDBObject("$in", values));

  10. DBCursor dbCursor = coll.find(queryCondition);

  11. assertEquals(2, dbCursor.size());

  12. assertEquals("tom", dbCursor.next().get("username"));

  13. }

  @Test
        public void testIn(){
                DBObject queryCondition = new BasicDBObject();          
                //age in [13, 47]
                queryCondition = new BasicDBObject();
                BasicDBList values = new BasicDBList();
                values.add(13);
                values.add(47);
                queryCondition.put("age", new BasicDBObject("$in", values));
                
                DBCursor dbCursor = coll.find(queryCondition);
                assertEquals(2, dbCursor.size());
                assertEquals("tom", dbCursor.next().get("username"));
        }


从以上几个例子可以看出,通过BasicDBList与BasicDBObject的相结合可以得出比较复杂的查询条件。

Java实现对MongoDB的AND、OR和IN操作 ,大于、小于等判断

标签:blog   http   io   os   使用   java   ar   strong   for   

原文地址:http://my.oschina.net/hetiangui/blog/314844

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!