How to get a particular element from MongoDB array?


You can use the aggregate framework to get a particular element from the MongoDB array. To understand the concept, let us create a collection with the document. The query to create a collection with the document is as follows −

> db.getParticularElement.insertOne({"InstructorName":"Larry","InstructorTechnicalSubject":["Java","C","C++","MongoDB","MySQL","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7ee027559dd2396bcfbfb1")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.getParticularElement.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c7ee027559dd2396bcfbfb1"),
   "InstructorName" : "Larry",
   "InstructorTechnicalSubject" : [
      "Java",
      "C",
      "C++",
      "MongoDB",
      "MySQL",
      "SQL Server"
   ]
}

Here is the query to get a particular element from an array −

> db.getParticularElement.aggregate([
   ... {
      ... $project:
      ... {
         ... ElementFromAnArray: 1,
         ... FourthElement: { $arrayElemAt: [ "$InstructorTechnicalSubject", 3] },
         ...
      ... }
   ... }
... ]);

The following is the output −

{ "_id" : ObjectId("5c7ee027559dd2396bcfbfb1"), "FourthElement" : "MongoDB" }

Updated on: 30-Jul-2019

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements