Getting only the first item for an array property in MongoDB?

To get only the first item from an array property in MongoDB, use the $slice operator in the projection stage. This operator limits the number of array elements returned in the query result.

Syntax

db.collection.find(
    { query },
    { arrayField: { $slice: 1 } }
);

Sample Data

db.gettingFirstItemInArrayDemo.insertOne({
    "UserId": 101,
    "UserName": "Carol",
    "UserOtherDetails": [
        {"UserFriendName": "Sam"},
        {"UserFriendName": "Mike"},
        {"UserFriendName": "David"},
        {"UserFriendName": "Bob"}
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cdfca52bf3115999ed51205")
}

Example: Get First Array Element

To retrieve only the first element from the UserOtherDetails array ?

db.gettingFirstItemInArrayDemo.find(
    {"UserId": 101}, 
    {UserOtherDetails: {$slice: 1}}
);
{
    "_id": ObjectId("5cdfca52bf3115999ed51205"),
    "UserId": 101,
    "UserName": "Carol",
    "UserOtherDetails": [
        {"UserFriendName": "Sam"}
    ]
}

Key Points

  • $slice: 1 returns only the first element of the array
  • $slice: -1 would return only the last element
  • The $slice operator works in the projection stage, not the query stage

Conclusion

The $slice operator effectively limits array elements in MongoDB query results. Use $slice: 1 in the projection to retrieve only the first item from any array property.

Updated on: 2026-03-15T01:29:42+05:30

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements