Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 } } Advertisements
