Create multiple indexes at a time

I need to build five indexes in a large MongoDB collection. I am familiar with the makeIndex operation, but I don’t know how to create all five indexes with a single command. Is it possible to create this package in MongoDB?

+6
source share
4 answers

It's pretty simple in the shell, there is an extension for the createIndexes collection, and you just pass the keys that you want to create indexes to.

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

Then it will 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" } ] > 
+3
source

You are mistaken, Mongo has a createIndexes command since version 2.6 (released before 2014).

https://docs.mongodb.com/v3.0/reference/command/createIndexes/

The documentation says that this requires one pass through the collection, so it should be about 5 times faster.

+2
source

There is no solution for this yet.

The background will prevent the database from being locked and allow other operations. But to start these operations, you will have to open a new mongo shell or run them asynchronously in the language of your choice (for example, js).

But if you need a strong consistency and you don't need to create background indexing ... you probably have to wait until your own MongoDB solution comes up.

0
source

I think this is not possible with a single command, but you can create your own script that will work the same way. If the size of your collection is large, I suggest that you separately create indexes with a background of true to reduce the likelihood of any locking problem.

 db.collection.ensureIndex( { a: 1 }, { background: true } ) 
-1
source

Source: https://habr.com/ru/post/982873/


All Articles