如何在 Java mongodb 驱动程序中使用“_id”字段查询文档?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9797935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to query documents using "_id" field in Java mongodb driver?
提问by user837208
I am trying to find documents in MongoDB by searching on "_id" key. My document looks like this-
我试图通过搜索“_id”键在 MongoDB 中查找文档。我的文件看起来像这样-
{
"_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.
BasicDBObject 的 append 方法支持 (String Key, Value),如果我将“_id”作为字符串传递给此方法,则不会匹配任何文档。
So my question is how do I pass "_id"?
所以我的问题是如何传递“_id”?
采纳答案by user837208
Solved it by using query as-
通过使用查询作为解决它 -
query.putAll((BSONObject)query);
回答by Chris
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).
不确定其他人是否可能正在寻找有关此主题的答案,但这是基于“_id”搜索 MongoDB 记录的最简单方法。MongoDB 文档未更新,并且仍将 ObjectId 显示为com.mongodb
包的一部分(它通常也没有提供有关按 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;
}
回答by Nifras Nipy
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);
回答by bogolyandras
For those who are seeking a more up to date method, especially with 3.4:
对于那些寻求更新方法的人,尤其是 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
}