Get the first element in an array and return using MongoDB Aggregate?


Use $unwind operator with $project for to get the first element in an array. Let us create a collection with documents. Following is the query

>db.getFirstElementInArrayDemo.insertOne({"StudentName":"John","StudentSubject":["MongoDB","Python","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c41292d6669774125244e")
}
>db.getFirstElementInArrayDemo.insertOne({"StudentName":"Chris","StudentSubject":["Java","C"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c413f2d6669774125244f")
}
>db.getFirstElementInArrayDemo.insertOne({"StudentName":"Robert","StudentSubject":["C++","Ruby"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c41532d66697741252450")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c9c41292d6669774125244e"),
   "StudentName" : "John",
   "StudentSubject" : [
      "MongoDB",
      "Python",
      "MySQL"
   ]
}
{
   "_id" : ObjectId("5c9c413f2d6669774125244f"),
   "StudentName" : "Chris",
   "StudentSubject" : [
      "Java",
      "C"
   ]
}
{
   "_id" : ObjectId("5c9c41532d66697741252450"),
   "StudentName" : "Robert",
   "StudentSubject" : [
      "C++",
      "Ruby"
   ]
}

Following is the query to get first element in an array and return using aggregate

> db.getFirstElementInArrayDemo.aggregate([
...    {$unwind:"$StudentSubject"},
...    {$group:{"_id":"$_id","FirstElement":{$first:"$StudentSubject"}}},
...    {$project:{"_id":0,"FirstElement":1}}
... ]);

This will produce the following output

{ "FirstElement" : "Java" }
{ "FirstElement" : "C++" }
{ "FirstElement" : "MongoDB" }

You can use $slice operator in find() to get the first element in the array. Following is the query

> db.getFirstElementInArrayDemo.find({},{"StudentSubject":{$slice:1}});

This will produce the following output

{ "_id" : ObjectId("5c9c41292d6669774125244e"), "StudentName" : "John", "StudentSubject" : [ "MongoDB" ] }
{ "_id" : ObjectId("5c9c413f2d6669774125244f"), "StudentName" : "Chris", "StudentSubject" : [ "Java" ] }
{ "_id" : ObjectId("5c9c41532d66697741252450"), "StudentName" : "Robert", "StudentSubject" : [ "C++" ] }

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements