aggregation _to find array element
aggregation _to find array element
```json
{
"_id": 1,
"name": "John Doe",
"items": [ "item1", "item2", "item3", "item4", "item5" ]
}
```
2. **To display the value at a specific position in the `items` array, use the following
aggregation pipeline:**
```javascript
db.myCollection.aggregate([
{ $match: { _id: 1 } }, // Match the document by _id or other criteria
{ $project: {
name: 1,
specificItem: { $arrayElemAt: ["$items", 2] } // Change 2 to the desired index
}
}
]);
```
In this example, `2` is the index of the element you want to retrieve (MongoDB
arrays are zero-indexed, so 2 refers to the third element, `"item3"`).
```json
{
"_id": 1,
"name": "John Doe",
"specificItem": "item3"
}
```
You can adjust the index value in the `$arrayElemAt` operator to get the element at
the desired position in the array. If you need to retrieve multiple specific elements,
you can modify the aggregation pipeline accordingly:
```javascript
db.myCollection.aggregate([
{ $match: { _id: 1 } }, // Match the document by _id or other criteria
{ $project: {
name: 1,
itemAtIndex2: { $arrayElemAt: ["$items", 2] }, // Change 2 to the desired index
itemAtIndex4: { $arrayElemAt: ["$items", 4] } // Change 4 to another desired
index
}
}
]);
```
This way, you can retrieve and display array values at specific positions in a
MongoDB document.