Java implements and, or, and in operations on MongoDB

Source: Internet
Author: User
Tags mongodb documentation

The introduction to Java operations in the official MongoDB documentation only provides a few simple examples. Although these examples can meet certain requirements, they are not completely complete yet. Below are some examples I wrote based on the prompts on the webpage.

1. background. The unit test form implemented in junit4.8.2. Test data:

{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"}

The initialization and cleanup of unit tests mainly involves establishing database connections, writing test data, and cleaning test data:

private static List<BasicDBObject> documents = new ArrayList<BasicDBObject>();private static DBCollection coll;@BeforeClasspublic 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 BasicDBObjectBasicDBObject dbObject = new BasicDBObject();Iterator<String> joKeys = jo.keys();while(joKeys.hasNext()){String key = joKeys.next();dbObject.put(key, jo.get(key));}documents.add(dbObject);}}@Beforepublic void setUp(){//Insert all data into MongoDBfor(BasicDBObject bdo : documents){coll.insert(bdo);}}@Afterpublic void cleanUp(){//Drop the collection to remove all data.//Note: it's not recommended.coll.drop();}

2. And is relatively simple.

@Testpublic void testAnd(){//agender='female' AND age > 27DBObject 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. Single field or operation.

@Testpublic void testOrSingleField(){DBObject queryCondition = new BasicDBObject();//age<15 OR age>27queryCondition = 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. The or operation between multiple fields

@Testpublic void testOrMultiFields(){DBObject queryCondition = new BasicDBObject();//agender=female OR age<=23queryCondition = 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 operation for a single field. For query conditions similar to where age = 13 or age = 47, you can use in instead

@Testpublic 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"));}

From the above examples, we can see that the combination of basicdblist and basicdbobject can produce complex query conditions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.