使用AND,OR条件查询Java中的MongoDB

时间:2014-09-08 07:56:34

标签: java mongodb logical-operators

我是MongoDB的新手,需要在Java中查询MongoDB。对于简单的查询,我可以编写等效的Java代码,但下面的查询有点复杂,并没有得到如何编写等效的Java代码。

以下是等效的MongoDB查询

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

此处,FILE_JOURNEY是集合。

1 个答案:

答案 0 :(得分:4)

可以这样写:

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