Building Multiple Indexes at Once

mongodb

Solution

This is pretty simple within the shell, there is a extention to the collection of `createIndexes` and you just pass in the keys you wish to create indexes on.

db.test.createIndexes([
        { "a" : 1 },
        { "b" : 1 },
        { "c" : 1 },
        { "d" : 1 },
        { "e" : 1 }
    ]);

This will then give us the following

> db.test.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.test"
        },
        {
                "v" : 2,
                "key" : {
                        "a" : 1
                },
                "name" : "a_1",
                "ns" : "test.test"
        },
        {
                "v" : 2,
                "key" : {
                        "b" : 1
                },
                "name" : "b_1",
                "ns" : "test.test"
        },
        {
                "v" : 2,
                "key" : {
                        "c" : 1
                },
                "name" : "c_1",
                "ns" : "test.test"
        },
        {
                "v" : 2,
                "key" : {
                        "d" : 1
                },
                "name" : "d_1",
                "ns" : "test.test"
        },
        {
                "v" : 2,
                "key" : {
                        "e" : 1
                },
                "name" : "e_1",
                "ns" : "test.test"
        }
]
>

Problem

I have a need to build five indexes in a large MongoDB collection. I'm familiar with the ensureIndex operation, but I do not know of a way to create all five of the indexes with a single command. Is this batch index creation possible in MongoDB?

Original source