List of indexed field(s) of collection and database in MongoDB

getIndexes() method is responsible for listing indexes of collection. You can find all indexes in the collection using getIndexes() method.

Syntex:


db.CollectionName. getIndexes()


Example: Suppose we have a collection Inventory as like below.


{ "_id" : 1, "item" : "item1", "qty" : 1, "BasePrice" : 300, "Price" : 500 }
{ "_id" : 2, "item" : "item1", "qty" : 2, "BasePrice" : 250, "Price" : 200 }
{ "_id" : 3, "item" : "item1", "qty" : 4, "BasePrice" : 250, "Price" : 300 }
{ "_id" : 4, "item" : "item1", "qty" : 8, "BasePrice" : 600, "Price" : 700 }
{ "_id" : 5, "item" : "item1", "qty" : 2, "BasePrice" : 502, "Price" : 500 }


Now use the following query to create an index on the item.


db.Inventory.createIndex( { item: 1 } )


Result:


{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1.0
}


Now run the following query to get a list of indexes in Inventory collection.


db.Inventory.getIndexes()


Result:


[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "Test.Inventory"
    },
    {
        "v" : 1,
        "key" : {
            "item" : 1.0
        },
        "name" : "item_1",
        "ns" : "Test.Inventory"
    }
]


Find all indexes in the database
You can list all indexes in the database with a collection name using the following query.


db.getCollectionNames().forEach(function(collection) {
   indexes = db[collection].getIndexes();
   print("Indexes for " + collection + ":");
   printjson(indexes);
});



 It will list all indexes in the database with a collection name.

No comments:

Post a Comment

PostgreSQL-Query: Sort result set by specific field values using ORDER BY Clause

Problem: Suppose we have a book_inventory table which has some columns such as id, isbn, title, author, publisher, publish_date, etc.. whe...