2015-10-14 38 views
-1

我創建了幾個文檔並插入到Mongo DB中。我使用相同的python。有沒有辦法讓我可以得到特定記錄的_id? 我知道我們在插入過程中得到_id。但是如果我需要在橫向間隔使用它,有沒有辦法通過使用find()命令來獲取它?在插入過程中查找其他文檔的_id

+0

當然你可以:) – sergiuz

+0

@SergiuZaharie請詳細說明 – TheFallenOne

+0

你想做什麼?每個文檔都有一個_id,當然你可以搜索一個文檔並顯示它的_id。 – sergiuz

回答

0

在Python中,你可以使用find_one()方法來獲取文檔和訪問_id屬性如下:

def get_id(value): 
    # Get the document with the record: 
    document = client.db.collection.find_one({'field': value}, {'_id': True}) 
    return document['_id'] 
0

插入記錄時,可以指定_id值。這也爲您在使用ReplicaSets時帶來了好處。

from pymongo.objectid import ObjectId 

client.db.collection.insert({'_id': ObjectId(), 'key1': value....})  

你可以存儲在一個列表中那些ID,如果你於需要_id要求插入後立即出現以後使用它。

相關問題