Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using java driver for Mongodb, how do you search for multiple values on the same field?

I'm somewhat new to mongo. I want to query on a field for multiple values. In SQL, I want something like this:

select * from table where field in ("foo","bar")

Suppose I have the following documents in mongodb

{
  "_id":"foo"
}
{
  "_id":"bar"
}

I simply want to mimic this query:

db.coll.find( { _id: { $in: [ "foo", "bar" ] } } );

I want to retrieve all documents whose _id is either "foo" or "bar". And I'd like to do this using the java driver.

I tried something like

BasicDBObject query = new DBObject()
query.append("_id","foo");
query.append("_id","bar");
collection.find(query);

But that seems to return only the "bar" document.

Please help

like image 808
kane Avatar asked Jul 24 '26 17:07

kane


1 Answers

To use the $in operator, it may be easier to use QueryBuilder to create the query like this:

QueryBuilder qb = new QueryBuilder();
qb.put("_id").in(new String[] {"foo", "bar"});
collection.find(qb.get());

or a little cleaner:

DBObject query = QueryBuilder.start("_id").in(new String[] {"foo", "bar"}).get();
collection.find(query);
like image 167
JohnnyHK Avatar answered Jul 28 '26 15:07

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!