繁体   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