Use the Ensureindex function to create an index of the collection.
For collections, each index needs to be created once, and duplicate creation has no effect;
> Show Collections System.indexes Users
The index metadata of all the databases is stored in the System.indexs collection;
Use the Getindexes function to view index information on a given collection:
> db.users.getindexes () [ { "V" : 1, "Key" : { "_id" : 1 }, "Name" : "_id_", "ns"  : "Blog.users" }, { "V" : 1, "Key" : { "username" : 1 }, "Name" : "Username_1", "ns"  : "Blog.users" }, { "V" : 1, "Key" : { "Age" : 1, "username" : 1 }, "name" : "Age_1_username_1", "ns" : "Blog.users" } ] >
The
can accommodate the Dropindex function to delete the specified index:
> db.users.dropindex ({"username": 1}) { "Nindexeswas" : 3, "OK" : 1 } > db.users.getindexes () [ { "V" : 1, "key"  : { "_id" : 1 }, "name" : "_id_", "ns" : "Blog.users" }, { "V" : 1, "Key" : { "Age"  : 1, " Username " : 1 }, "name" : "Age_1_username_1", "ns" : "Blog.users" } ] >
In the example above, you can see that the index's identity default format is Keyname1_dir1_keyname2_dir....keynamen_dirn;
You can also specify an identity name:
> db.users.ensureindex ({"username": 1},{"name": "FirstName"}) { "Createdcollectionautomatically" : false, "Numindexesbefore" : 2, " Numindexesafter " : 3, " OK " : 1 } > db.users.getindexes () [ { " V " : 1, " key " : { "_id"  : 1 }, "name" : "_id_", "ns" : "Blog.users" }, { "V" : 1, "Key" : { "Age" : 1, "username" : 1 }, "name" : "Age_1_username_1", "ns" : "Blog.users" }, { "V" : 1, "Key" : { "username" : 1 }, "Name" : "FirstName", "ns" : "Blog.users" } ] >
To modify an index: Delete index, CREATE index;
Dropping an index allows you to specify the index identity directly, for example:
> db.users.dropindex ("FirstName") { "Nindexeswas" : 3, "OK" : 1 } > db.users.getindexes () [ { " V " : 1, " key " : { "_id"  : 1 }, "name" : "_id_", "ns" : "Blog.users" }, { "V" : 1, "Key" : { "Age" : 1, "username" : 1 }, "name" : "Age_1_username_1", "ns" : "Blog.users" } ] >
This article is from the "Margin with Wish" blog, please be sure to keep this source http://281816327.blog.51cto.com/907015/1600882
Index management for MongoDB learning Note 22 MongoDB