50

I am trying to find documents in MongoDB by searching on "_id" key. My document looks like this-

{
  "_id" : ObjectId("4f693d40e4b04cde19f17205"),
  "hostname" : "hostnameGoesHere",
  "OSType" : "OSTypeGoesHere"
}

I am trying to search this document as-

ObjectId id= new ObjectId("4f693d40e4b04cde19f17205");        
BasicDBObject obj = new BasicDBObject();        
obj.append("_id", id);        
BasicDBObject query = new BasicDBObject();        
query.putAll(query);

But I get below error-

error: reference to putAll is ambiguous, both method putAll(Map) in BasicBSONObject and method putAll(BSONObject) in BasicBSONObject match
        query.putAll(query);

The append method of BasicDBObject supports (String Key, Value) and if I pass "_id" as String to this method, no documents are matched.

So my question is how do I pass "_id"?

0

8 Answers 8

71

Not sure if others might be searching for answers on this topic, but here is the easiest way to search for a MongoDB record based on "_id". The MongoDB documentation is not updated and still shows ObjectId as being part of the com.mongodb package (it also generally does not give a lot of information on searching by ObjectId).

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is it outdated?
34

For those who are seeking a more up to date method, especially with 3.4:

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;

import static com.mongodb.client.model.Filters.eq;

//......
MongoCollection<Document> myCollection = database.getCollection("myCollection");
Document document = myCollection.find(eq("_id", new ObjectId("4f693d40e4b04cde19f17205"))).first();
if (document == null) {
    //Document does not exist
} else {
    //We found the document
}

3 Comments

can we use findOne here?
I don't think that we can use that method anymore. That was part of the old API api.mongodb.com/java/2.14/com/mongodb/DBCollection.html The new is a slightly different one api.mongodb.com/java/3.0/com/mongodb/async/client/…
the eq is not applicable to 3.12?
6

You can do this

 ObjectId id= new ObjectId("4f693d40e4b04cde19f17205");        
    BasicDBObject obj = new BasicDBObject();        
    obj.append("_id", id);        
    BasicDBObject query = new BasicDBObject();        
    query.putAll((BSONObject)query);

Comments

2

The more simple way to do this is:

Bson filter = Filters.eq("_id", new ObjectId("4f693d40e4b04cde19f17205"));
mongoConfig.getMongoTemplate().getCollection("myCollection").find(filter);

Reference here: https://www.baeldung.com/mongodb-query-documents-id

Comments

1

Solved it by using query as-

query.putAll((BSONObject)query);

Comments

0

I found a way around, with a little bit more of code, requires a string representing the id to be found passed as argument.

import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import org.bson.conversions.Bson;
import org.bson.Document;
import org.bson.types.ObjectId;   

[...]

public static void findCustomerById(String id) {
    try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
        MongoDatabase database = mongoClient.getDatabase("database_name");
        Bson filter = Filters.eq("_id", new ObjectId(id));
        MongoCollection<Document> collection = database.getCollection("customer");

        //Tries to find the document
        Document doc = collection. Find(filter).first();
        //prints the document
        System.out.println(doc.toJson());
    } catch (Exception e) {
        System.out.println("Error finding document");
        System.out.println("Error in: " + e.getMessage());
        e.printStackTrace();
    }

Comments

0

Don't forget to add the collectionName parameter if your class and collectionName don't match. I landed on this question because my _id query wasn't working even though it looked good at first blush.

Comments

-2

You can try this snippet:

ObjectId id= new ObjectId("4f693d40e4b04cde19f17205");        
BasicDBObject obj = new BasicDBObject();        
obj.append("_id", id);        
BasicDBObject query = new BasicDBObject();        
query.putAll((BSONObject)obj);

1 Comment

How is this different from Nifras Nipy's answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.