Querying MongoDB in Java with AND,OR condition

淺唱寂寞╮ 提交于 2020-06-01 04:01:06

问题


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.


回答1:


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 );


来源:https://stackoverflow.com/questions/25719671/querying-mongodb-in-java-with-and-or-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!