MongoDB

MongoDB $First and $FirstN Operators

The $first and $firstN operators are the aggregation pipeline method of MongoDB. The $first aggregation operator allows us to determine the first value in an array. The $first operator only takes the array as an input parameter. The $firstN operator returns a preset number of entries from the starting index of an array. The number that is specified to the $firstN operator cannot be less than “1”. Moreover, the $firstN operator gives the original array if the defined number is greater than or equal to the values of the array.

How to Use the $First and $FirstN Operators in MongoDB

The $first and $firstN operators are used in MongoDB to get the required number of elements from the array of documents. The $first and $firstN operators only resolve the array fields in the documents of the MongoDB collection. We are working with the “FoodItems” collection in this MongoDB article. We add the documents in the “FoodItems” collection which also contains the array field on which the $first and $firstN operators function. The command to add the documents is represented here which uses the insertMany() method for the insertion at the same time.

db.FoodItems.insertMany([
      {
          "_id": 1,
          "name":"Fruits",
          "list": ["Apple", "Mango", "Cherry", "kiwi"],
          "price": 350
      },
       {
           "_id": 2,
          "name":"Vegetables",
          "list": ["Beetroot", "Radish", "Turnip", "Carrot."],
          "price": 255
      },
       {
          "_id": 3,
          "name":"Snack Food",
          "list": ["Popcorn", "Salted peanuts", "Fries", "Baked sweets", "Chocolates"],
          "price": 400
      },
   {
         "_id": 4,
          "name":"Beverages",
          "list": ["Lemonade", "Milkshake", "Iced tea", "Coffee", "Water", "Hot chocolate"],
          "price": 550
      },
       {"_id": 5,
          "name":"Sea Food",
          "list": null,
          "price": 300
}
  ])

Now, the results of inserting the documents are displayed in the following which acknowledge “true” and indicate that all the documents are inserted without any error in the specified collection:

{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
}

Example 1: Using the MongoDB $First Operator to Get the First Value of the Array

As we already discussed, the $first operator collects the first element from the array field of the specified document. In the example, we use the $first operator of MongoDB to retrieve the first array field value from all the documents which are inserted in the “FoodItems” collection. We deploy the aggregate command where the $project operator is specified. The $project operator adds the new “firstItem” field which has the $first operator along with the expression. The $first operator takes the name of the “$list” array field to get the first element.

db.FoodItems.aggregate([
  {
    $project: {
        "firstItem": {
          $first: "$list"
        }
    }
  }
])

We can see that the $first operator returns the first value from the “$list” array of all the documents.

[
  { _id: 1, firstItem: 'Apple' },
  { _id: 2, firstItem: 'Beetroot' },
  { _id: 3, firstItem: 'Popcorn' },
  { _id: 4, firstItem: 'Lemonade' },
  { _id: 5, firstItem: null }
]

Example 2: Using the MongoDB $First Operator for the Invalid Operand

We know that the $first operator only handles the arrays. But the $first operator arises from providing an invalid operand. Here, we have an example of giving an invalid operand in the $first operator to raise the expectation. We use the same query as in the previous example, but the difference is in the $first operator where the expression is changed. Instead of giving the array field from the documents, we input the “$price” field which does not contain the array elements. When the query is executed, the error is generated.

db.FoodItems.aggregate([
  {
    $project: {
        "Item": {
          $first: "$price"
        }
    }
  }
])

The following MongoDB error occurs because the $price field is not an array. The $first operator in MongoDB only deals with the arrays as mentioned in the following error:

MongoServerError: PlanExecutor error during aggregation :: caused by :: $first's argument must be an array, but is int

Example 3: Using the MongoDB $First Operator for the Missing and Null Values of the Array

The $first operator returns null if the argument is an empty array field or a missing array field. We match the document which holds the “_id” value “5” because it contains the null array element. After that, we set the $first operator in the $project operator field, “firstListValue”. The $first operator has the input “$list” array field to get its first item.

db.FoodItems.aggregate([
   {$match: {"_id": 5}},
    {$project: {
        "firstListValue": {
          $first: "$list"
        }
    }
  }
])

As we have seen in the “_id: 5” document, the $list array field contains the null value. When the previous $first operator is run in the shell, it gives the null value.

[ { _id: 5, firstListValue: null } ]

Example 4: Using the MongoDB $FirstN Operator for the Nth Values of the Array

Now, we fetch the required number of elements from the array field. For this, we have the $firstN operator whose implementation is slightly different from the $first operator based on the functionality. There, we define the “_id: 3” expression in the $match operator to match the document with this expression. Then, we have a new “firstListValue” field which is included within the $project operator. The new “firstListValue” field is employed with the $firstN operator where the “input” and “n” arguments are set. The “input” argument has the name of the “$lists” array field. The “n” argument has the integer value of “2” which indicates the number of the elements which are fetched from the provided array field.

db.FoodItems.aggregate([
   {$match: {"_id": 3}},
    {$project: {
        "firstListValue": {
          $firstN: {input:"$list", n:2}
        }
    }
  }
])

We obtained two elements from the following “$list” array as the number is specified to the $firstN operator:

[ { _id: 3, firstListValue: [ 'Popcorn', 'Salted peanuts' ] } ]

Example 5: Using the MongoDB $First Operator for the Nth Value of an Array with the Condition

Additionally, the “n” argument of the $firstN operator can be assigned with a value dynamically. The “n” parameter has a conditional statement which is associated with it that informs it to retrieve the specified element from the array when the condition is satisfied. Consider the following command of the $firstN operator. We provide the $match operator with “_id:2” document to be matched for the $firstN operator. After that, we insert the “firstListValue” field inside the $project operator. Next, we have a $firstN operator in the projected “firstListValue” field along with its parameter.

The “input” is the first parameter set in the $firstN operator with the “$list” field. Then, the “n” parameter is specified with the $cond operator which sets the if-else condition. Inside the “if”, we have another condition which is “{$gt: [“$price”, 550] }”. If the $price is greater than the value of “550”, the “1” element is retrieved. Otherwise, the “else” option displays “3” elements.

db.FoodItems.aggregate([
{ $match:{ _id: 2}},
   {$project: {
         "firstListValue": {
           $firstN: {input:"$list",
      n: { $cond: { if: {$gt: ["$price", 550] }, then: 1, else: 3 }}
       }
     }
   }
}
 ])

The $firstN operator outputs three elements of the $list array because the $price value is “350” of the given document which is not greater than the specified value.

[ { _id: 2, firstListValue: [ 'Beetroot', 'Radish', 'Turnip' ] } ]

Conclusion

This article explored the MongoDB $first and the $firstN operators. First, the $first operator examples are provided with the different cases. The example of the $first operator obtained the first value of the array. Then, the $first operator returns the null value since the array field has the missing value. After that, the $first operator exception example is given for an invalid argument. The $firstN operator is specified to collect the nth elements from the array. Furthermore, the $firstN operator collects the elements based on the condition which is given to the “n” parameter.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.