简体   繁体   English

如果密钥并不总是存在,如何在 mongodb 中查找_one?

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

I have a following mongodb:我有以下 mongodb:

some records looks like {'_id': ObjectId('62790ce20375a639af1d8676'), 'visit_id': 594817704, 'transaction' : 10}有些记录看起来像{'_id': ObjectId('62790ce20375a639af1d8676'), 'visit_id': 594817704, 'transaction' : 10}

some has only this form: {'_id': ObjectId('62790ce20375a639af1d8679'), 'visit_id': 594817704}有些只有这种形式: {'_id': ObjectId('62790ce20375a639af1d8679'), 'visit_id': 594817704}

Using this code I can search for all collections that consists of transaction_id:使用此代码,我可以搜索包含 transaction_id 的所有集合:

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

But if I would like to get a record with specific transaction_id, this code does not work (it tooks infinite time to search):但是,如果我想获得具有特定 transaction_id 的记录,则此代码不起作用(搜索需要无限时间):

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

I tried to combine both approaches, that is to firstly ask if transaction_id exists and then search for transaction_id = 10, but it did not work:我尝试将这两种方法结合起来,即先询问transaction_id是否存在,然后搜索transaction_id = 10,但没有成功:

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

How can I fix it, please?请问我该如何解决?

collection.findOne({transaction_id: 10})

should work.应该管用。

No need for $exists if you want a specific value.如果您想要一个特定的值,则不需要$exists

See how it works on the playground example看看它在操场上的例子是如何工作的

How big is your data set?你的数据集有多大? do you have an index on transaction_id ?你有关于transaction_id的索引吗?

If your query is slow, consider add an hashed index on transaction_id .如果您的查询速度很慢,请考虑在transaction_id上添加哈希索引。 Without the index, the DB should check all documents to see if any of them has transaction_id: 1000 .如果没有索引,数据库应检查所有文档以查看其中是否有任何文档具有transaction_id: 1000 This is O(n) operations where n is the number of your documents.这是O(n)操作,其中n是您的文档数。 The index stores this information, so it will be one check only O(1) .索引存储此信息,因此只需O(1)一次检查。

In order to create the index use the UI or, using the shell:为了创建索引,请使用 UI 或使用 shell:

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

Where you replace <collectionName> with your collection name.您将<collectionName>替换为您的集合名称的位置。

Please refer my code.请参考我的代码。

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)

To create index创建索引

collection.create_index("transaction_id");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM