问题
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