Array index or indexing inner items in MongoDB to fetch values

MongoDBDatabaseBig Data Analytics

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 } }
raja
Published on 02-Apr-2020 06:23:09
Advertisements