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

Building multiple indexes with one of them being unique in Mongo

这是 的延续,我目前正在使用以下命令

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,"name":1},
     {"uId" : "hashed"},
     {"uId" : 1,"products":1},
     {"bId" : 1}
   ],
   {
     unique: true
   }
)

This is in continuation to ,

有一个 provided the reference to createIndexes,createIndexes命令采用runCommand的形式: 你可以使用,syntax and example

  • 更改 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_"
        }
    ]
  }
)