- 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
Array index or indexing inner items in MongoDB to fetch values
At first, let us create a collection with documents and also use ensureIndex() to create an index −
> db.demo323.insertOne({"details":{"Name":"Chris","Age":34}}); { "acknowledged" : true, "insertedId" : ObjectId("5e51157af8647eb59e56206e") } > db.demo323.insertOne({"details":{"Name":"David","Age":31}}); { "acknowledged" : true, "insertedId" : ObjectId("5e511581f8647eb59e56206f") } > db.demo323.insertOne({"details":{"Name":"Bob","Age":28}}); { "acknowledged" : true, "insertedId" : ObjectId("5e511589f8647eb59e562070") } > db.demo323.ensureIndex({"details.Name":1}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo323.find();
This will produce the following output −
{ "_id" : ObjectId("5e51157af8647eb59e56206e"), "details" : { "Name" : "Chris", "Age" : 34 } } { "_id" : ObjectId("5e511581f8647eb59e56206f"), "details" : { "Name" : "David", "Age" : 31 } } { "_id" : ObjectId("5e511589f8647eb59e562070"), "details" : { "Name" : "Bob", "Age" : 28 } }
Following is the query to find values from the array −
> db.demo323.find({"details.Name":"Bob"});
This will produce the following output −
{ "_id" : ObjectId("5e511589f8647eb59e562070"), "details" : { "Name" : "Bob", "Age" : 28 } }
- Related Articles
- MongoDB query to fetch array values
- How do I index “or” in MongoDB for indexing multiple fields?
- Accessing array values in a MongoDB collection to fetch a specific document
- How to sort inner array in MongoDB?
- Fetch specific field values in MongoDB
- Remove values in an array by comparing the items 0th index in JavaScript?
- MongoDB to fetch documents with $or Operator
- Insert data into inner array in MongoDB?
- Multi-key Indexing on an entire array with MongoDB?
- How to count items in array with MongoDB?
- Accessing inner element of JSON array in MongoDB?
- Create a record array from a (flat) list of array and fetch specific values based on index in Numpy
- Query an array in MongoDB to fetch a specific value
- Clearing items in a nested MongoDB array?
- MongoDB find by multiple array items?

Advertisements