beboy beboy - 5 months ago 25
Java Question

writing mongodb syntax on java api

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..

here the error
enter image description here

Answer

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