Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

How to query documents using "_id" field in Java mongodb driver?

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"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...