Extract subarray value in MongoDB?

To extract a subarray value in MongoDB, you can use the $elemMatch projection operator to return only the first array element that matches the specified condition.

Syntax

db.collection.find(
    { query },
    { arrayField: { $elemMatch: { field: "value" } } }
);

Sample Data

Let us first create a collection with documents ?

db.extractSubArrayDemo.insertOne({
    _id: 101,
    "clientName": "Larry",
    "ClientDetails": [
        {
            "ClientProjectName": "Online Game",
            "DeveloperTeamSize": 10
        },
        {
            "ClientProjectName": "Pig Dice Game",
            "DeveloperTeamSize": 12
        },
        {
            "ClientProjectName": "Web Student Tracker",
            "DeveloperTeamSize": 11
        }
    ]
});
{ "acknowledged": true, "insertedId": 101 }

Display all documents from the collection ?

db.extractSubArrayDemo.find().pretty();
{
    "_id": 101,
    "clientName": "Larry",
    "ClientDetails": [
        {
            "ClientProjectName": "Online Game",
            "DeveloperTeamSize": 10
        },
        {
            "ClientProjectName": "Pig Dice Game",
            "DeveloperTeamSize": 12
        },
        {
            "ClientProjectName": "Web Student Tracker",
            "DeveloperTeamSize": 11
        }
    ]
}

Example: Extract Specific Array Element

Extract only the "Pig Dice Game" project details from the ClientDetails array ?

db.extractSubArrayDemo.find(
    { '_id': 101 },
    { 
        _id: 0, 
        ClientDetails: { $elemMatch: { ClientProjectName: 'Pig Dice Game' } }
    }
).pretty();
{
    "ClientDetails": [
        {
            "ClientProjectName": "Pig Dice Game",
            "DeveloperTeamSize": 12
        }
    ]
}

Key Points

  • $elemMatch returns only the first matching array element.
  • The result still wraps the matched element in an array format.
  • Use _id: 0 to exclude the document ID from results.

Conclusion

The $elemMatch projection operator effectively extracts specific subarray elements based on field conditions. It's particularly useful when you need only one matching element from large arrays instead of the entire array.

Updated on: 2026-03-15T00:48:18+05:30

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements