mongodbmongodb-indexesmongo-collection

Building multiple indexes with one of them being unique in Mongo


This is in continuation to Building Multiple Indexes at Once, where I am currently making use of the following commands

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})

I want to understand what is the correct way of transforming this into a single command to be executed at the server. My failed attempts are as follows:

#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
   }
)

Solution

  • This is in continuation to Building Multiple Indexes at Once,

    There is a answer provided the reference to createIndexes, The createIndexes command takes the form of runCommand: you could use, syntax and example,

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