Reputation: 6017
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
Upvotes: 3
Views: 5574
Reputation: 311865
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);
Upvotes: 5