3

I created mongo db collection index using java code

dbCollection.createIndex("accountNumber");

When i see indices using

db.accounts.getIndexes()

I am getting the index name as "accountNumber_1"

How to get the index name also same as document field? or how to give index name?

Is naming indices important or i can ignore this?

2
  • Is there any specific reason you need to use the index name? When you hint to mongo which index to use in a query, you specify the field name that is indexed - not the actual index name: db.users.find().hint( { age: 1 } ) Commented Jan 19, 2016 at 8:46
  • 1
    you can ignore this. the name is of no consequence Commented Jan 19, 2016 at 8:48

2 Answers 2

2

When we create index on the document users

> db.users.createIndex({name: 1})
{
        "ok" : 0,
        "errmsg" : "Index with name: name_1 already exists with different option
s",
        "code" : 85
}

the name: name_1 is returned, then we can get the index through getIndexes()

> db.users.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.users"
        },
        {
                "v" : 1,
                "unique" : true,
                "key" : {
                        "name" : 1
                },
                "name" : "name_1",
                "ns" : "test.users",
                "background" : true,
                "safe" : null
        }
]

We know, the name_1 is just the value of index name. and the key name is used to create index for document users. I think the name_1 is the value of name to meet BSON structure. We can ignore it...

Sign up to request clarification or add additional context in comments.

Comments

0

You can create index with the name you wanted using the other variant of createIndex method, refer java API here.


public void createIndex(DBObject keys,
                        DBObject options)
Creates an index on the field specified, if that index does not already exist.
Prior to MongoDB 3.0 the dropDups option could be used with unique indexes allowing documents with duplicate values to be dropped when building the index. Later versions of MongoDB will silently ignore this setting.

Parameters: keys - a document that contains pairs with the name of the field or fields to index and order of the index options - a document that controls the creation of the index. MongoDB documentation Index Creation Tutorials

You can corresponding mongodb documentation here.

Basically the second parameter 'options' contain an option to supply index name explicitly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.