- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a nested index in MongoDB?
To create nested index in MongoDB, you can use createIndex() or ensureIndex(). The syntax is as follows −
db.yourCollectionName.createIndex({"yourOuterFieldName.yourInnerFieldName.yourSecondInnerFieldName": 1});
To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.nestedIndexDemo.insertOne( ... { ... ... "CustomerId":101, ... "CustomerDetails": ... { ... "CustomerListDetails": ... { ... "CustomerName":"Larry", ... "CustomerProjectName": "Project-1", ... "CustomerCountryName":"US" ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c8fc565d3c9d04998abf010") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.nestedIndexDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8fc565d3c9d04998abf010"), "CustomerId" : 101, "CustomerDetails" : { "CustomerListDetails" : { "CustomerName" : "Larry", "CustomerProjectName" : "Project-1", "CustomerCountryName" : "US" } } }
Here is the query to create a nested index in MongoDB:
> db.nestedIndexDemo.createIndex({"CustomerDetails.CustomerListDetails.CustomerCountryName": 1}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
Here is the query to display index −
> db.nestedIndexDemo.getIndexes();
The following is the output −
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.nestedIndexDemo" }, { "v" : 2, "key" : { "CustomerDetails.CustomerListDetails.CustomerCountryName" : 1 }, "name" : "CustomerDetails.CustomerListDetails.CustomerCountryName_1", "ns" : "test.nestedIndexDemo" } ]
- Related Articles
- How to create double nested array in MongoDB?
- Creating an index on a nested MongoDB field?
- How to create an index with MongoDB?
- Create index in a MongoDB collection?
- How to create an index in MongoDB using Java?
- How to retrieve a nested object in MongoDB?
- How to create a nested JSplitPane in Java?
- Create an index for text search in MongoDB
- How to create nested Python dictionary?
- How to create nested while loop in C#?
- Change a unique index to a sparse unique index in MongoDB?
- How to add new item in nested array with MongoDB?
- Clearing items in a nested MongoDB array?
- Write a MongoDB query to get nested value?
- Increment a value in a MongoDB nested object?

Advertisements