【问题标题】:Building multiple indexes with one of them being unique in Mongo构建多个索引,其中一个在 Mongo 中是唯一的
【发布时间】:2021-01-22 07:36:56
【问题描述】:

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

【问题讨论】:

  • ...在单独的调用中一一执行创建索引语句有什么问题?
  • @TimBiegeleisen 我不想说任何错误的东西,但要完成创建索引,有时每个索引几乎需要几个小时(几乎是重新索引用例)一次(单屏) 然后一次性跟踪所有进度。

标签: mongodb mongodb-indexes mongo-collection


【解决方案1】:

这是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_"
        }
    ]
  }
)

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 2015-02-24
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2014-02-24
    • 2016-01-18
    相关资源
    最近更新 更多