📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
- How to Create Indexes: createIndex()
- How to Find Indexes: getIndexes()
- How to Drop Indexes: dropIndex()
1. How to Create Indexes: createIndex()
Syntax:
db.collection_name.createIndex({field_name: 1 or -1})
- The value 1 is for ascending order and -1 is for descending order.
- The db.collection.createIndex() method only creates an index if an index of the same specification does not already exist.
- MongoDB indexes use a B-tree data structure.
Example
> db.posts.createIndex({title: 1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.posts.createIndex({title: 1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.posts.find().pretty();
{
"_id" : ObjectId("5e184a067695f4d696a0598d"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "Java Guides",
"url" : "https://javaguides.net",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("5e184a067695f4d696a0598e"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "Java Guides",
"url" : "https://javaguides.net",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T09:35:00Z"),
"like" : 0
}
]
}
{
"_id" : ObjectId("5e18544a7695f4d696a0598f"),
"title" : "MongoDB CRUD Operations",
"description" : "MongoDB CRUD Operations",
"by" : "Java Guides",
"url" : "https://javaguides.net",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T09:35:00Z"),
"like" : 0
}
]
}
How to Find Indexes: getIndexes()
Syntax
db.collection_name.getIndexes()
Example
> db.posts.getIndexes();
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydb.posts"
},
{
"v" : 2,
"key" : {
"title" : 1
},
"name" : "title_1",
"ns" : "mydb.posts"
}
]
How to Drop Indexes: dropIndex()
Dropping a specific index
db.collection_name.dropIndex({index_name: 1})
> db.posts.dropIndex({title: 1});
{ "nIndexesWas" : 2, "ok" : 1 }
Dropping all the indexes:
db.collection_name.dropIndexes()
> db.posts.dropIndexes();
{
"nIndexesWas" : 1,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}
Comments
Post a Comment
Leave Comment