Select the first element in an array in MongoDB

In this MongoDB tutorial, we are going to learn to “select the first element in an array in MongoDB” with a few examples. We will cover this by performing various operations with examples. The following list topics we are going to cover in this tutorial:

  • How to select the first element in an array in MongoDB query
  • Select the first element in an array in MongoDB using an example
  • How to select the first element in an array in MongoDB with condition
  • Select the first element in an array using MongoDB using
  • Select the first element in an array in MongoDB using python

How to select the first element in an array in MongoDB query

MongoDB provides the $first aggregation function to select the first element in an array.

Syntax:

{ $first: <expression> }

Here, the <expression> can be any valid expression as it resolves to an array, null or missing.

The $first operator is an alias for the following $arrayEleAt expression:

{ $arrayElemAt: [ <array expression>, 0 ] }

Notes:

The valid operand for $first must resolve to an array, null, or missing:

  • If the operand resolves to a non-empty array then the $first returns the first element in the array.
  • If the operand resolves to an empty array [] then the $first does not return a value.
  • If the operand is null or missing then the $first returns null.

Also, check: MongoDB aggregate $count

Select the first element in an array in MongoDB an example

In this topic, you will learn to select the first element in an array from the documents of the MongoDB collection. Let’s get understand this with the help of an example.

Example:

In this example, we will also cover the Non-empty, null and missing concepts as well.

We create a collection called test with the following documents:

db.test.insertMany([
{"_id": 1, "rank": [ 1, 2, 3 ] },   // Non-empty array
{"_id": 2, "rank": [ [ ] ] },       // Non-empty array
{"_id": 3, "rank": [ null ] },      // Non-empty array
{"_id": 4, "rank": [ ] },           // Empty array
{"_id": 5, "rank": null },          // Is null
{"_id": 6 }                         // Is Missing
])

After that, we will apply the below query to select the first element of an array using the $first operator.

db.test.aggregate([
   { $addFields: { firstElem: { $first: "$rank" } } }
])

Here, we have used the aggregate operation in which the $addFields added a new field firstElem whose value is derived from applying the $first operator to the rank field.

After execution, It returns the following documents:

Select the first element in an array in MongoDB example
Select the first element in an array in MongoDB example

We have successfully obtained the first element of an array and added it with the documents of field firstElem.

Read: MongoDB get collection size

How to select the first element in an array in MongoDB with condition

In this topic, you will learn to find the first element in an array in the MongoDB collection. For this, MongoDB provides the $first operator to access the first element in an array and along with the $first operator you will also learn about the $last operator to access the last element in an array. Let’s get understand this with the help of an example.

Example:

In this example, we will use the $first and $last operator on the array to retrieve the information.

We have created a sample collection running with the following documents:

db.running.insertMany([
{"_id": 1, "team": "Anteater", log: [ { run: 1, distance: 8 }, { run2: 2, distance: 7.5 }, { run: 3, distance: 9.2 } ] },
{"_id": 2, "team": "Bears", log: [ { run: 1, distance: 18 }, { run2: 2, distance: 17 }, { run: 3, distance: 16 } ] },
{"_id": 3, "team": "Cobras", log: [ { run: 1, distance: 2 } ] },
{"_id": 4, "team": "Deer", log: [ { run: 1, distance: 13 }, { run2: 2, distance: 19 }, { run: 3, distance: 23 } ] }
])

After that, we will apply the below query to select the first element in an array in the MongoDB collection.

db.running.aggregate([
   { $addFields: { firstrun: { $first: "$log" }, lastrun: { $last: "$log" } } }
])

Here, we have used aggregate operation and used the $first and $last operator on the log array to retrieve the information for the first run and the last run.

How to select the first element in an array in MongoDB with
How to select the first element in an array in MongoDB with

We have successfully obtained the first and last element of an array and added it with the documents of field firstrun and lastrun respectively.

Read: $in MongoDB Example

Select the first element in an array using MongoDB using

In this topic, you will understand to select the first element in an array of the MongoDB collection. MongoDB provides one more aggregation function $arrayElemAt that returns the element at the specified array index. Let’s get understand this with the help of an example and select the first element in an array.

Syntax of $arrayElemAt:

{ $arrayElemAt: [ <array>, <idx> ] }

Here, the <array> expression resolves to an array and the <idx> expression resolves to an integer.

Example:

We will insert the following documents into the users’ collection that contain the following documents:

db.users.insertMany([
{ "_id" : 1, "name" : "Isabella", favorites: [ "chocolate", "cake", "butter", "apples" ], "city" : "United States" },
{ "_id" : 2, "name" : "Peter", favorites: [ "apples", "pudding", "pie" ], "city" : "Canada" },
{ "_id" : 3, "name" : "Olivia", favorites: [ "pears", "pecans", "chocolate", "cherries" ], "city" : "Australia" },
{ "_id" : 4, "name" : "Emma", favorites: [ "ice cream" ], "city" : "USA" }
])

After inserting the documents, we will apply the below query to return the first element in the favorites array:

db.users.aggregate([
   {
     $project:
      {
         name: 1,
         first: { $arrayElemAt: [ "$favorites", 0 ] }
      }
   }
])

Here, we have used the aggregate operation where $arrayElemAt will select the first elements from the $favorites array.

Select the first element in an array using MongoDB using
Select the first element in an array using MongoDB using

We have successfully obtained the first element of an array using $arrayElemAt and added it with the documents of the field first.

Read: Current date in MongoDB

Select the first element in an array in MongoDB using python

In this topic, you will learn to select the first element in an array in MongoDB using Python. We will use the MongoDB driver PyMongo to access the MongoDB database. Let’s get understand this followed by an example and select the first element in an array from the MongoDB collection using python.

Example:

The following documents were inside the details collection. And, You can also retrieve the documents by using the find() method.

db.details.find()
{ "_id" : 1, "item" : "journal", "qty" : 15, "tags" : [ "appliances", "school", "clothing" ] }
{ "_id" : 2, "item" : "notebook", "qty" : 20, "tags" : [ "school" ] }
{ "_id" : 3, "item" : "paper", "qty" : 25, "tags" : [ "appliances", "school" ] }
{ "_id" : 4, "item" : "planner", "qty" : 30, "tags" : [ "school", "appliances" ] }
{ "_id" : 5, "item" : "postcard", "qty" : 20, "tags" : [ [ "appliances", "school" ], "clothing" ] 

Now, we will use the following block of python code to select the first element in an array of existing details collection:

import pymongo

# creating a MongoClient object and connect with the host
myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017")

# accessing the database
mydb = myclient["info"]

# accessing the collection of the database
mycol = mydb["details"]

# return the nested array documents
collect = mycol.aggregate([
  { "$project": 
      { "item": 1, 
        "firstElem": { "$arrayElemAt": [ "$tags", 0 ] } 
      } 
  } 
])
for first in collect:
    print(first)

In the code, we have imported the pymongo library to access the MongoDB driver.

  • After that, connect with the server.
  • Access the MongoDB details collection of the info database.
  • After that, we have applied the $arrayElemAt aggregate operation and defined the index value 0 to access the first element of the array.

Check the output:

Select the first element in an array in MongoDB using python
Select the first element in an array in MongoDB using python

We have successfully obtained the first element of an array using the $arrayElemAt operator using python and added it with the documents of the field firstElem.

You may also like to read the following tutorials on MongoDB.

I hope you have learned about selecting the first element in an array in MongoDB with a few examples and cover the below topics:

  • How to select the first element in an array in MongoDB query
  • Select the first element in an array in MongoDB using an example
  • How to select the first element in an array in MongoDB with condition
  • Select the first element in an array using MongoDB using
  • Select the first element in an array in MongoDB using python