问题描述
这是对 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
的形式:
你可以使用,syntax 和 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_"
}
]
}
)