Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

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

$
0
0
getIndexes() method is responsible to list indexes of collection. You can find all indexes in 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 following query to create index on item.


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


Result:


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


Now run the following query to get 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 database
You can list all index in database with collection name using following query.


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



 It will list all indexes in database with collection name.

Viewing all articles
Browse latest Browse all 265

Trending Articles