Reputation: 103
How do I write this query on java api ? ',' means 'or' clause
db.questions.find( { user_id: /bc/ },{user_name:/bc/},{age:/2/} )
I've tried different ways, but I've been successful using one option only. How to add multiple options using "or" clause ?
here my code :
MongoClient mongoClient;
DB db;
DBCollection table;
DBCursor cursor = null;
mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("stackoverflow");
boolean auth = db.authenticate("aku", "kamu".toCharArray());
table = db.getCollection("questions");
cursor = table.find(new BasicDBObject("user_id", java.util.regex.Pattern.compile("milk")));
while (cursor.hasNext()) {
DBObject object = cursor.next();%>
out.print(object.get("user_id"));
}
Using mySQL, the query is :
select * from questions where user_id like '%bc%' or user_name like %bc% or age like %2%
I'm new to mongoDB, I feel like it's fairly hard to convert queries from mySQL..
Upvotes: 1
Views: 135
Reputation: 1035
I'm not sure if your question is already answered but if you're using a later version or mongodb java driver, it can be written this way. I'm not familiar with how BasicDBObject works, am more used to Documents. Both works.
List<Document> orQueryList = new ArrayList<Document>();
orQueryList.add("user_id", "bc");
orQueryList.add("user_name", "bc");
orQueryList.add("age", "2");
Document orDoc = new Document("$or", orQueryList);
MongoCursor<Document> cursor = table.find(orDoc).iterator();
while (cursor.hasNext()) {
Document dbObj = cursor.next();
System.out.println(dbObj.getString("user_id");
}
Upvotes: 0
Reputation: 4363
You can use the $or
operator - manual link
db.questions.find( "{ $or : [user_id: '/bc/' ,user_name:'/bc/',age:'/2/'] }")
You can use this query within java like this:
FindIterable<Document> iterable = db.getCollection("questions").find( "{ $or : [user_id: '/bc/' ,user_name:'/bc/',age:'/2/'] }" );
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
Upvotes: 2