Logical Querying MongoDB Java Example

This post will focus on the logical Logical Querying MongoDB Java Example
operators that are available in
momgodb.I will use Java for the
illustration purpose of these
operators. You can use any of
the language for which mongo
driver is available. For the comparison operators you can refer the previous post here.
There are 4 logical operators that have been documented in mongodb specs.
We will continue with the same example that we have seen in the previous post.

{
   "_id" : ObjectId("534d965b6c36724f0d3075be"),
   "firstName" : "kevin",
   "lastName" : "ryan",
   "founder" : "mongo",
   "wiki" : "http://en.wikipedia.org/wiki/Kevin_P._Ryan",
   "hits" : 32000
}

Logical Querying MongoDB Java

Logical Operators :

  1. $or operator : OR operator works exactly in the same way as Boolean OR, it will return you the documents matching any of the criteria passed with the OR query argument.
    //or operator - hits > 90000 || hits < 40000
    BasicDBObject searchObject = new BasicDBObject();
    List<BasicDBObject> searchArguments = new ArrayList<BasicDBObject>();
    searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$lt",40000)));
    searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$gt",90000)));
    searchObject.put("$or", searchArguments);
  2. $and operator : AND operator works exactly in the same way as Boolean AND ,it will return you the documents matching all the criteria passed with the AND query argument.
    //and operator -	hits > 40000 && founder = 'Spring'
    BasicDBObject searchObject = new BasicDBObject();
    searchArguments.clear();
    searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$gt",40000)));
    searchArguments.add(new BasicDBObject("founder","Spring"));
    searchObject.put("$and", searchArguments);
  3. $not operator: NOT operator works exactly same as Boolean logical not operator , it will return you all the documents not matching the criteria passed with the NOT query argument. Kindly note that it will also returns you the documents that don’t have the fields in which we are querying.
    Important thing to note about NOT operator is that it can’t operate independently as ‘OR’ and ‘AND’, we have to use this operator in conjunction with other operators. 

    //not operator -returns ( hits > 40000 && founder !='Spring') + All the documents where 'founder' key is missing
    BasicDBObject searchObject = new BasicDBObject();
    searchArguments.clear();
    searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$gt",40000)));
    searchArguments.add(new BasicDBObject("founder",new BasicDBObject("$not",new BasicDBObject("$eq","Spring"))));
    searchObject.put("$and", searchArguments);
  4. $nor operator : NOR operator works exactly same as Boolean logical NOR operator , it will return you all the documents not matching all the criteria’s passed with the NOR query argument.
    //nor operator - !(hits > 40000 || founder ='Spring')
    BasicDBObject searchObject = new BasicDBObject();
    searchArguments.clear();
     searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$gt",40000)));
    searchArguments.add(new BasicDBObject("founder",new BasicDBObject("$eq","Spring")));
    searchObject.put("$nor", searchArguments);

Complete Code :

/**
 * 
 */
package com.lotusmedia.mongo;

import java.util.ArrayList;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;

/**
 * @author j.saurab
 *
 */
public class LogicalQueriesExample {

   private static void logicalQueryOperators(){
	   DBCollection lotusCollection=MongoUtils.getCollection("lotusCollection");
	   BasicDBObject searchObject = new BasicDBObject();

	   //or operator - hits > 90000 || hits < 40000
	   List<BasicDBObject> searchArguments = new ArrayList<BasicDBObject>();
	   searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$lt",40000)));
	   searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$gt",90000)));
	   searchObject.put("$or", searchArguments);
	   DBCursor logicalQueryResults = lotusCollection.find(searchObject);		
		while(logicalQueryResults.hasNext()){
			System.out.println("OR operator Result --->"+logicalQueryResults.next());
		}

	   //and operator -	hits > 40000 && founder = 'Spring'
	   searchObject = new BasicDBObject();
	   searchArguments.clear();
	   searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$gt",40000)));
	   searchArguments.add(new BasicDBObject("founder","Spring"));
	   searchObject.put("$and", searchArguments);
	   logicalQueryResults = lotusCollection.find(searchObject);		
		while(logicalQueryResults.hasNext()){
			System.out.println("AND Operator Result --->"+logicalQueryResults.next());
		}

	   //not operator -returns ( hits > 40000 && founder !='Spring') + All the documents where 'founder' key is missing
	   searchObject = new BasicDBObject();
	   searchArguments.clear();
	   searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$gt",40000)));
	   searchArguments.add(new BasicDBObject("founder",new BasicDBObject("$not",new BasicDBObject("$eq","Spring"))));
	   searchObject.put("$and", searchArguments);
	   logicalQueryResults = lotusCollection.find(searchObject);		
		while(logicalQueryResults.hasNext()){
			System.out.println("NOT Operator Result --->"+logicalQueryResults.next());
		}

		//nor operator - !(hits > 40000 || founder ='Spring')
	   searchObject = new BasicDBObject();
	   searchArguments.clear();
	   searchArguments.add(new BasicDBObject("hits",new BasicDBObject("$gt",40000)));
	   searchArguments.add(new BasicDBObject("founder",new BasicDBObject("$eq","Spring")));
	   searchObject.put("$nor", searchArguments);
	   logicalQueryResults = lotusCollection.find(searchObject);		
	   while(logicalQueryResults.hasNext()){
			System.out.println("NOR Operator Result --->"+logicalQueryResults.next());
		}
   }

	public static void main(String[] args) {
		LogicalQueriesExample.logicalQueryOperators();
	}

}

Disclaimer : All the above used images belong to their respective owners and used only for reference

Logical Querying MongoDB Java


 

Let'sConnect

Saurabh Jain

A Developer working on Enterprise applications ,Distributed Systems, Hadoop and BigData.This blog is about my experience working mostly on Java technologies ,NoSQL ,git , maven and Hadoop ecosystem.
Let'sConnect

One thought on “Logical Querying MongoDB Java Example

Add Comment Register



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>