January 27, 2017

How to check if database exists while connecting in HSQLDB

In HSQLDB, if while providing connection string if the database does not exists, it creates a new database. However, lets say if we want to restrict HSQLDB to create new Database and only connect to exists one and if not present then throw back an exception, we can specify a connection property ifexists=true. This will allow only to connect to an existing database and avoid creating new one. Also, if db does not exists it will throw an exception.

 Connection c = DriverManager.getConnection( "jdbc:hsqldb:file:testdb;ifexists=true", "SA", "");  

January 25, 2017

How to compare two fields value while querying in mongodb

To compare 2 fields of a document while querying in mongodb, we need to use $where.

Lets see the example to compare 2 fields of a document:

 Employee Collection  
           {    
             "_id" : 1,    
             "name" : {    
                "first" : "Abhi",    
                "last" : "Dev"    
             },    
             "department" : "finance",    
             "joineddate" : "2010-04-10"     
            },    
            {    
             "_id" : 2,    
             "name" : {    
                "first" : "Agrawal",    
                "last" : "Agrawal"    
             },     
             "joineddate" : "2006-07-07"     
            },    
            {    
             "_id" : 3,    
             "name" : {    
                "first" : "Dhruv",    
                "last" : "Agrawal"    
             },    
             "department" : "finance",    
             "joineddate" : "2010-09-07"     
            }  
           }   

Now lets say I need to fetch data which has first and last values are equal.

The query would be:
 db.employee.find({ $where : "this.name.last == this.name.first" })  

The output would be:
{    
             "_id" : 2,    
             "name" : {    
                "first" : "Agrawal",    
                "last" : "Agrawal"    
             }