python - PyMongo 创建具有 2 个或更多字段的唯一索引

标签 python mongodb mongodb-query pymongo

如何在 pymongo 中创建具有 2 个字段的索引,以便一起唯一?

我有这个代码:

self.db[self.mongo_collection].create_index("url", unique=True)

但我需要对 urlcategory 保持唯一性。

最佳答案

您需要创建一个复合索引并将 unique 设置为 True,如 documentation 中所述:

If you use the unique constraint on a compound index, then MongoDB will enforce uniqueness on the combination of values rather than the individual value for any or all values of the key.

self.db[self.mongo_collection].create_index(
    [("url", pymongo.DESCENDING), ("category", pymongo.ASCENDING)],
    unique=True
)

关于python - PyMongo 创建具有 2 个或更多字段的唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812685/

相关文章:

python - 从索引矩阵填充矩阵

Node.js 与 mongo - 渲染 "object"而不是模板内的数据?

node.js - 使用 Node Js 聚合管道在 mongodb 中创建价格范围

python - 如何模糊 3d matplotlib 中的点

python - 自动将照片上传到特定的 Google 相册相册

python - 使用 python 使用 for 循环导入文本文件

ruby-on-rails - 如何将 Mongoid _id 转换为时间戳 (Rails)

ruby-on-rails - 如何直接从 Ruby 查询 MongoDB 而不是使用 Mongoid?

java - mongodb java聚合操作

MongoDB:在集合中的数百万条记录上查找 count() 命令的执行时间?