MongoDB query to find property of first element of array?

MongoDBDatabaseBig Data Analytics

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" } ] }
raja
Published on 30-Apr-2019 09:04:05
Advertisements