Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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
   }
)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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,

  • change your real database name in Your database name and collection name in 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_"
        }
    ]
  }
)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!