簡體   English   中英

如果密鑰並不總是存在,如何在 mongodb 中查找_one?

[英]How to find_one in mongodb if the key is not always present?

我有以下 mongodb:

有些記錄看起來像{'_id': ObjectId('62790ce20375a639af1d8676'), 'visit_id': 594817704, 'transaction' : 10}

有些只有這種形式: {'_id': ObjectId('62790ce20375a639af1d8679'), 'visit_id': 594817704}

使用此代碼,我可以搜索包含 transaction_id 的所有集合:

collection.find({'transaction_id': { "$exists":True }

但是,如果我想獲得具有特定 transaction_id 的記錄,則此代碼不起作用(搜索需要無限時間):

collection.find({'transaction_id': 10})

我嘗試將這兩種方法結合起來,即先詢問transaction_id是否存在,然后搜索transaction_id = 10,但沒有成功:

collection.find({'transaction_id': { "$exists":True }, 'transaction_id': 10})

請問我該如何解決?

collection.findOne({transaction_id: 10})

應該管用。

如果您想要一個特定的值,則不需要$exists

看看它在操場上的例子是如何工作的

你的數據集有多大? 你有關於transaction_id的索引嗎?

如果您的查詢速度很慢,請考慮在transaction_id上添加哈希索引。 如果沒有索引,數據庫應檢查所有文檔以查看其中是否有任何文檔具有transaction_id: 1000 這是O(n)操作,其中n是您的文檔數。 索引存儲此信息,因此只需O(1)一次檢查。

為了創建索引,請使用 UI 或使用 shell:

db.getCollection(<collectionName>).createIndex( {transaction_id: "hashed" })

您將<collectionName>替換為您的集合名稱的位置。

請參考我的代碼。

from pymongo import MongoClient

client = MongoClient('localhost', 27017);

#connect to the DB named testdb
mydatabase = client.testdb

#pickup collection named transactions 
collection = mydatabase.transactions

#find one by transaction_id
res = collection.find_one({transaction_id:10})

#display data
print(res)

創建索引

collection.create_index("transaction_id");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM