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:
$arrayElemAtis used to access the first element ofmyArrayby using0as the index.$matchfilters the documents based on whether the first element equalsdesiredValue.
Make sure to replace "desiredValue" with the actual value you want to filter by.
