MongoDB query to find property of first element of array?


You can use $slice operator for this. Let us first create a collection with documents −

> db.firstElementOfArray.insertOne(
...    {
...       _id: 100,
...       "Details": [
...          {
...             "CustomerName": "John",
...             "CustomerCountryName":"US"
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 100 }
> db.firstElementOfArray.insertOne(
...    {
...       _id: 101,
...       "Details": [
...          {
...             "CustomerName": "Carol",
...             "CustomerCountryName":"UK"
...          },
...          {
...             "CustomerName": "David",
...             "CustomerCountryName":"AUS"
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{
   "_id" : 100,
   "Details" : [
      {
         "CustomerName" : "John",
         "CustomerCountryName" : "US"
      }
   ]
}
{
   "_id" : 101,
   "Details" : [
      {
         "CustomerName" : "Carol",
         "CustomerCountryName" : "UK"
      },
      {
         "CustomerName" : "David",
         "CustomerCountryName" : "AUS"
      }
   ]
}

Following is the query to find property of first element of array −

> db.firstElementOfArray.find({},{'Details':{$slice:1},'Details.CustomerName':1}).pretty();

This will produce the following output −

{ "_id" : 100, "Details" : [ { "CustomerName" : "John" } ] }
{ "_id" : 101, "Details" : [ { "CustomerName" : "Carol" } ] }

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

840 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements