构建多个索引,其中之一在 Mongo 中是唯一的

问题描述

这是对 Building Multiple Indexes at Once 的延续,我目前正在使用以下命令

db.test_collection_data.createIndex({"uId" : 1,"name" : 1},{unique : 1})
db.test_collection_data.createIndex({"uId" : "hashed"})
db.test_collection_data.createIndex({"uId" : 1,"products" : 1})
db.test_collection_data.createIndex({"bId" : 1})

我想了解将其转换为要在服务器上执行的单个命令的正确方法是什么。我失败的尝试如下:

#uniqueness is lost for the first index
db.test_collection_data.createIndexes(
   [
     {"uId" : 1,"name":1},{"uId" : "hashed"},{"uId" : 1,"products":1},{"bId" : 1}
   ]
)


#unable to create since products are not really unique
db.test_collection_data.createIndexes(
   [
     {"uId" : 1,{"bId" : 1}
   ],{
     unique: true
   }
)

解决方法

这是对Building Multiple Indexes at Once的延续,

有一个 answer 提供了对 createIndexes 的引用,createIndexes 命令采用 runCommand 的形式: 你可以使用,syntaxexample

  • 更改您在 Your database name 中的真实数据库名称和 test_collection_data 中的集合名称,
db.getSiblingDB("Your database name").runCommand(
  {
    createIndexes: "test_collection_data",indexes: [
        {
            key: {
                "uId": 1,"name": 1
            },unique : true,name: "_uId_name_"
        },{
            key: {
                "uId": "hashed"
            },name: "_uId_"
        },{
            key: {
                "uId": 1,"products": 1
            },name: "_uId_products_"
        },{
            key: {
                "bId": 1
            },name: "_bId_"
        }
    ]
  }
)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...