简体   繁体   中英

Querying MongoDB in Java with AND,OR condition

I am newbie to MongoDB and need to query MongoDB in Java. For simple queries, I can write the equivalent Java code but the below query is a little complex and not getting how to write equivalent Java code.

Below is the equivalent MongoDB query

db.FILE_JOURNEY.find(  {$and :[ {
                                    $or: [ { SUBSCRIBERID: "225136298" }, { SUBSCRIBERID : null} ]
                                },      
                                {   
                                    $or: [ { BATCHID : "615060299" }, { FILENAME : "TR.NYHBE.834Q.D.212311980342.QHP.dat" } ]  
                                }
                              ] 
                        } 
                    )

Here, FILE_JOURNEY is the collection.

It can be written like this:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB( DBNAME );

DBCollection collection = db.getCollection( "FILE_JOURNEY" );

DBObject subscriberId = new BasicDBObject( "SUBSCRIBERID", "225136298" );
DBObject subscriberIdIsNull = new BasicDBObject( "SUBSCRIBERID", null );
BasicDBList firstOrValues = new BasicDBList();
firstOrValues.add( subscriberId );
firstOrValues.add( subscriberIdIsNull );
DBObject firstOr = new BasicDBObject( "$or", firstOrValues );

DBObject batchId = new BasicDBObject( "BATCHID", "615060299" );
DBObject fileName = new BasicDBObject( "FILENAME", "TR.NYHBE.834Q.D.212311980342.QHP.dat" );
BasicDBList secondOrValues = new BasicDBList();
secondOrValues.add( batchId );
secondOrValues.add( fileName );
DBObject secondOr = new BasicDBObject( "$or", secondOrValues );
BasicDBList andValues = new BasicDBList();
andValues.add( firstOr );
andValues.add( secondOr );

DBObject query = new BasicDBObject( "$and", andValues );

DBCursor cursor = collection.find( query );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM