Tutorial by Examples

db.people.createIndex({name: 1}) This creates an ascending single field index on the field name. In this type of indexes the sort order is irrelevant, because mongo can traverse the index in both directions.
db.people.createIndex({name: 1, age: -1}) This creates an index on multiple fields, in this case on the name and age fields. It will be ascending in name and descending in age. In this type of index, the sort order is relevant, because it will determine whether the index can support a sort opera...
To drop an index you could use the index name db.people.dropIndex("nameIndex") Or the index specification document db.people.dropIndex({name: 1})
db.people.getIndexes() This will return an array of documents each describing an index on the people collection
See the below transactions collection. > db.transactions.insert({ cr_dr : "D", amount : 100, fee : 2}); > db.transactions.insert({ cr_dr : "C", amount : 100, fee : 2}); > db.transactions.insert({ cr_dr : "C", amount : 10, fee : 2}); > db.transactions.in...
If index name is known, db.collection.dropIndex('name_of_index'); If index name is not known, db.collection.dropIndex( { 'name_of_field' : -1 } );
db.collection.getIndexes(); Output [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "documentation_db.transactions" }, { "v&quo...
db.collection.createIndex( { "user_id": 1 }, { unique: true } ) enforce uniqueness on the defined index (either single or compound). Building the index will fail if the collection already contains duplicate values; the indexing will fail also with multiple entries missing the field (sin...
Sparse indexes: These can be particularly useful for fields that are optional but which should also be unique. { "_id" : "[email protected]", "nickname" : "Johnnie" } { "_id" : "[email protected]" } { "_id" : "julia@example...

Page 1 of 1