Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if an index is unique in Mongo on the command line

Tags:

mongodb

I'm working with a collection that someone else created, and I need to find out whether an index is unique. Is there anyway to do this from the mongo shell?

like image 299
dave Avatar asked Jun 23 '11 13:06

dave


People also ask

Is MongoDB index unique?

A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields. By default, MongoDB creates a unique index on the _id field during the creation of a collection.

How do I query unique records in MongoDB?

To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.

How do you check if indexes are being used in MongoDB?

You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection. Result: The output contains the default _id index and the user-created index student name index.

How can you tell if an index was used with a query MongoDB?

Use the db. collection. explain() or the cursor. explain() method in executionStats mode to return statistics about the query process, including the index used, the number of documents scanned, and the time the query takes to process in milliseconds.


2 Answers

You can search for indexes with:

db.system.indexes.find();

To search for a unique index:

db.system.indexes.find({"unique": true});

With that, you can also add more search parameters to find specific indexes by namespace, key, etc.

Edit: Relevant documentation: http://www.mongodb.org/display/DOCS/Index-Related+Commands

like image 187
Andz Avatar answered Nov 09 '22 22:11

Andz


db.<my_collection>.getIndexes()

If some of those indexes are unique, you will see a key named "unique" with the value true.

like image 41
Manur Avatar answered Nov 10 '22 00:11

Manur