ACEG
ACEG

Reputation: 2041

MongoDB: Querying by ObjectId with Java Driver

Using MongoDB with the Java driver, I have a collection users that I want to query based on their ObjectId (the big picture: I am extrapolating from ObjectId to the object's creation timestamp).

The problem is, querying by ObjectId does not seem to work: I always get no results. For testing purposes, I have hardcoded in the search query the ObjectId of an existing user from the database, just to be sure that I should get results:

{ "_id": ObjectId("565ef85ee4b0a4db3c2fc96b"), ... }

Still, I never get any results.

These are the ways I have tried to build the query, together with the printout of the created query:

1.

BasicDBObject query = new BasicDBObject();
query.put("_id", "565ef85ee4b0a4db3c2fc96b");

Query: { "_id" : "565ef85ee4b0a4db3c2fc96b"}

2.

BasicDBObject query = new BasicDBObject();
query.put("_id", new ObjectId("565ef85ee4b0a4db3c2fc96b"));

Query: { "_id" : { "$oid" : "565ef85ee4b0a4db3c2fc96b"}}

3.

BasicDBObject query = new BasicDBObject("_id", "565ef85ee4b0a4db3c2fc96b");

Query: { "_id" : "565ef85ee4b0a4db3c2fc96b"}

4.

BasicDBObject query = new BasicDBObject("_id", new ObjectId("565ef85ee4b0a4db3c2fc96b"));

Query: { "_id" : { "$oid" : "565ef85ee4b0a4db3c2fc96b"}}

5.

DBObject query = new BasicDBObject("_id", 
        BasicDBObjectBuilder.start("$gte", new ObjectId("565ef85ee4b0a4db3c2fc96b")).get());

Query: { "_id" : { "$gte" : { "$oid" : "565ef85ee4b0a4db3c2fc96b"}}}

My application is deployed on OpenShift and I manually tried the queries in the RockMongo GUI; I get the same empty result. However, if I manually search for { "_id" : ObjectId("565ef85ee4b0a4db3c2fc96b")}, I get the correct result.

My question is: how can I correctly build the query so that it works?

Or, how can I get the Java Driver to produce an ObjectId("...") instead of an {"$oid": "..."} ?

Upvotes: 4

Views: 5977

Answers (2)

Darren Parker
Darren Parker

Reputation: 1812

I prefer this style from @ImbaBalboa answer

import static com.mongodb.client.model.Filters.eq;
import org.bson.Document;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
Document myDoc = collection.find(eq("_id", new ObjectId("565ef85ee4b0a4db3c2fc96b"))).first();

Upvotes: 0

Alex
Alex

Reputation: 21766

The code snippet below shows how you can query a Mongo collection by _id. Please note that { "$oid": "<id>" } is the strict equivalent of ObjectId( "<id>" ). Strict mode representations of BSON types conform to the JSON RFC and allows any JSON parser to process these strict mode representations as key/value pairs.

import org.bson.types.ObjectId;

public DBObject findDocumentById(String id) {
    BasicDBObject query = new BasicDBObject();
    query.put("_id", new ObjectId(id));
    DBObject dbObj = collection.findOne(query);
    return dbObj;
 }

Upvotes: 5

Related Questions