
- MongoDB Tutorial
- MongoDB - Home
- MongoDB - Overview
- MongoDB - Advantages
- MongoDB - Environment
- MongoDB - Data Modeling
- MongoDB - Create Database
- MongoDB - Drop Database
- MongoDB - Create Collection
- MongoDB - Drop Collection
- MongoDB - Data Types
- MongoDB - Insert Document
- MongoDB - Query Document
- MongoDB - Update Document
- MongoDB - Delete Document
- MongoDB - Projection
- MongoDB - Limiting Records
- MongoDB - Sorting Records
- MongoDB - Indexing
- MongoDB - Aggregation
- MongoDB - Replication
- MongoDB - Sharding
- MongoDB - Create Backup
- MongoDB - Deployment
- MongoDB - Java
- MongoDB - PHP
- Advanced MongoDB
- MongoDB - Relationships
- MongoDB - Database References
- MongoDB - Covered Queries
- MongoDB - Analyzing Queries
- MongoDB - Atomic Operations
- MongoDB - Advanced Indexing
- MongoDB - Indexing Limitations
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - Text Search
- MongoDB - Regular Expression
- Working with Rockmongo
- MongoDB - GridFS
- MongoDB - Capped Collections
- Auto-Increment Sequence
- MongoDB Useful Resources
- MongoDB - Questions and Answers
- MongoDB - Quick Guide
- MongoDB - Useful Resources
- MongoDB - Discussion
Create index in a MongoDB collection?
To create index, use createIndex() in MongoDB. Let us create a collection with documents −
> db.demo702.createIndex({"details.id":1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo702.insertOne({ ... "details" : [ ... { ... id:101, ... studentInfo:{ ... "StudentName" : "Chris", ... "StudentAge" : 23, ... } ... }, ... { ... ... id: 102, ... studentInfo:{ ... "StudentName" : "Robert", ... "StudentAge" : 20, ... } ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ea3b551299a9f98c93b3") }
Display all documents from a collection with the help of find() method −
> db.demo702.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ea6ea3b551299a9f98c93b3"), "details" : [ { "id" : 101, "studentInfo" : { "StudentName" : "Chris", "StudentAge" : 23 } }, { "id" : 102, "studentInfo" : { "StudentName" : "Robert", "StudentAge" : 20 } } ] }
- Related Articles
- How to create a new collection in MongoDB?
- How to create a nested index in MongoDB?
- How to create a MongoDB collection using Java?
- Add field that is unique index to collection in MongoDB?
- Create an index for text search in MongoDB
- How to create an index with MongoDB?
- Clone a collection in MongoDB?
- How to create an index in MongoDB using Java?
- How to create a collection correctly in MongoDB to avoid “ReferenceError: Not defined” error?
- Renaming column name in a MongoDB collection?
- How to drop a collection in MongoDB?
- Group by dates in a MongoDB collection?
- How to index my collection to use a compound multikey index?
- Change collection name in MongoDB?
- Change a unique index to a sparse unique index in MongoDB?

Advertisements