2012-03-21 158 views
28

我想通過搜索「_id」鍵在MongoDB中查找文檔。我的文件看起來像這個 -如何使用Java mongodb驅動程序中的「_id」字段查詢文檔?

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

我想這個文件搜索原樣

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

,但我得到下面的錯誤 -

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

BasicDBObject支持的追加方法(String鍵,值),如果我將「_id」作爲字符串傳遞給此方法,則不會匹配任何文檔。

所以我的問題是如何通過「_id」?

+0

對方回答更多的幫助了我。也許你接受這個... – Ohmen 2016-02-26 19:08:11

回答

3

通過查詢解決它原樣

query.putAll((BSONObject)query); 
48

不知道其他人可能會尋找關於這個主題的答案,但這裏是尋找基於「_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; 
} 
0

你可以做到這一點

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

對於那些誰正在尋找一個更加最新的方法,尤其是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 
} 
相關問題