简体   繁体   English

使用Python的“set()”类型的Mongodb

[英]Mongodb with Python's “set()” type

I am building a web App with mongoDB as the backend. 我正在构建一个以mongoDB作为后端的Web应用程序。 Some of the documents need to store a collection of items in some sort of list, and then the system will need to frequently check if a specified item is present in that list. 某些文档需要在某种列表中存储项目集合,然后系统需要经常检查该列表中是否存在指定项目。 Using Python's 'in' operator takes Big-O(N) time, n being the size of the list. 使用Python的'in'运算符需要Big-O(N)时间,n是列表的大小。 Since these list can get quite large, I want something faster than that. 由于这些列表可能会变得非常大,我想要比这更快的东西。 Python's 'set' type does this operation in constant time (and enforces uniqueness, which is good in my case), but is considered an invalid data type to put in MongoDB. Python的'set'类型在恒定时间内执行此操作(并强制执行唯一性,这在我的情况下很好),但被认为是放在MongoDB中的无效数据类型。

So what's the best way to do this? 那么最好的方法是什么? Is there some way to just use a regular list and exploit mongo's indexing features? 有没有办法只使用常规列表并利用mongo的索引功能? Again, I want to know, for a given document in a collection, does a list inside that document contain particular element? 同样,我想知道,对于集合中的给定文档,该文档中的列表是否包含特定元素?

You can represent a set using a dictionary. 您可以使用字典表示集合。 Your elements become the keys, and all the values can be set to a constant such as 1. The in operator checks for the existence of a key. 您的元素成为键,所有值都可以设置为常量,例如1. in运算符检查键的存在。

EDIT. 编辑。 MongoDB stores a dict as a BSON document, where the keys must be strings (with some additional restrictions), so the above advice is of limited use. MongoDB将dict存储为BSON文档,其中键必须是字符串(有一些额外的限制),因此上述建议的用途有限。

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

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