如果键并不总是存在,如何在mongodb中找到_one?
我有一个以下mongodb:
某些记录看起来像{'_ ID':ObjectID('62790CE20375A639AF1D8676'),'visit_id':594817704,'trasmaction':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})
我该如何修复它?
I have a following mongodb:
some records looks like {'_id': ObjectId('62790ce20375a639af1d8676'), 'visit_id': 594817704, 'transaction' : 10}
some has only this form: {'_id': ObjectId('62790ce20375a639af1d8679'), 'visit_id': 594817704}
Using this code I can search for all collections that consists of 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):
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:
collection.find({'transaction_id': { "$exists":True }, 'transaction_id': 10})
How can I fix it, please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该工作。
如果您想要特定的值,则不需要
$ $。
请查看其在 Playground示例示例
您的数据集有多大的方面?您在
transaction_id
上有索引吗?如果查询速度很慢,请考虑添加
transaction_id
上的哈希索引。如果没有索引,数据库应检查所有文档,以查看它们是否具有
transaction_id:1000
。这是o(n)
操作,其中n
是您的文档数量。该索引存储此信息,因此仅检查o(1)
。为了创建索引,请使用UI或使用shell:
在其中您将
< collectionName>
用收集名称替换。should work.
No need for
$exists
if you want a specific value.See how it works on the playground example
How big is your data set? do you have an index on
transaction_id
?If your query is slow, consider add an hashed index on
transaction_id
.Without the index, the DB should check all documents to see if any of them has
transaction_id: 1000
. This isO(n)
operations wheren
is the number of your documents. The index stores this information, so it will be one check onlyO(1)
.In order to create the index use the UI or, using the shell:
Where you replace
<collectionName>
with your collection name.请参考我的代码。
创建索引
Please refer my code.
To create index