How to filter by first element?

QuestionsQuestions8 SkillsProQuery MongoDB ArraysNov, 08 2025
0119

To filter documents in MongoDB based on the first element of an array, you can use the $arrayElemAt operator in a similar way as with the last element. Here's an example of how to do this:

Assuming you have a collection named myCollection and you want to filter documents where the first element of an array field named myArray is equal to a specific value, you can use the following aggregation query:

db.myCollection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          { $arrayElemAt: ["$myArray", 0] }, // Get the first element of the array
          "desiredValue" // Replace with the value you want to match
        ]
      }
    }
  }
]);

In this query:

  • $arrayElemAt is used to access the first element of myArray by using 0 as the index.
  • $match filters the documents based on whether the first element equals desiredValue.

Make sure to replace "desiredValue" with the actual value you want to filter by.

0 Comments

no data
Be the first to share your comment!