How to get a particular element from MongoDB array?

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 28-Mar-2019 12:19:35
Advertisements