Display only an element found in an array in MongoDB?

To display only an element found in an array in MongoDB, use aggregate() with $match, $unwind, and $project stages to filter and extract specific array elements.

Syntax

db.collection.aggregate([
    { "$match": { "arrayField.searchField": "searchValue" }},
    { "$unwind": "$arrayField" },
    { "$match": { "arrayField.searchField": "searchValue" }},
    { "$project": { "fieldToDisplay": "$arrayField.fieldName", "_id": 0 }}
]);

Sample Data

db.demo204.insertOne({
    "_id": 101,
    "Name": "Chris",
    "Age": 23,
    "details": [
        {
            "id": "1001",
            "empId": "John_1001",
            "salary": "50000",
            "Technology": "Java"
        },
        {
            "id": "1002",
            "empId": "John_1002"
        },
        {
            "id": "1003",
            "empId": "John_10003",
            "salary": "60000",
            "Technology": "MongoDB"
        }
    ]
});
{ "acknowledged": true, "insertedId": 101 }

Display All Documents

db.demo204.find();
{
    "_id": 101, "Name": "Chris", "Age": 23, "details": [
        { "id": "1001", "empId": "John_1001", "salary": "50000", "Technology": "Java" },
        { "id": "1002", "empId": "John_1002" },
        { "id": "1003", "empId": "John_10003", "salary": "60000", "Technology": "MongoDB" }
    ]
}

Example: Extract Technology for ID "1001"

db.demo204.aggregate([
    { "$match": { "details.id": "1001" }},
    { "$unwind": "$details" },
    { "$match": { "details.id": "1001" }},
    { "$project": { "Technology": "$details.Technology", "_id": 0 }}
]);
{ "Technology": "Java" }

How It Works

  • First $match: Filters documents containing the target array element
  • $unwind: Deconstructs the array into separate documents
  • Second $match: Filters the unwound documents to match the specific element
  • $project: Displays only the required field from the matched element

Conclusion

The aggregation pipeline efficiently extracts specific array elements by combining match, unwind, and project stages. This approach allows precise filtering and display of targeted data from complex nested arrays.

Updated on: 2026-03-15T01:43:45+05:30

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements