Find in MongoDB documents with filled nested array and reshape the documents result

To find MongoDB documents with filled nested arrays and reshape the results, use the aggregation pipeline with $unwind, $project, and $match operators. This approach filters out empty nested objects and transforms the document structure.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $project: { fieldName: "$arrayField.nestedField" } },
    { $match: { fieldName: { $exists: true } } }
]);

Create Sample Data

db.demo187.insertMany([
    {
        "_id": "101",
        "Details": [
            { "Subject": "MongoDB" },
            { "Subject": "MySQL" }
        ]
    },
    {
        "_id": "102",
        "Details": [
            { }
        ]
    },
    {
        "_id": "103",
        "Details": [
            { "Subject": "MongoDB" },
            { "Subject": "MySQL" }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": "101",
        "1": "102", 
        "2": "103"
    }
}

Display All Documents

db.demo187.find();
{ "_id": "101", "Details": [ { "Subject": "MongoDB" }, { "Subject": "MySQL" } ] }
{ "_id": "102", "Details": [ { } ] }
{ "_id": "103", "Details": [ { "Subject": "MongoDB" }, { "Subject": "MySQL" } ] }

Find Documents with Filled Nested Arrays

db.demo187.aggregate([
    { $unwind: "$Details" },
    { $project: { Subject: "$Details.Subject" } },
    { $match: { Subject: { $exists: true } } }
]);
{ "_id": "101", "Subject": "MongoDB" }
{ "_id": "101", "Subject": "MySQL" }
{ "_id": "103", "Subject": "MongoDB" }
{ "_id": "103", "Subject": "MySQL" }

How It Works

  • $unwind: Deconstructs the Details array, creating a separate document for each array element
  • $project: Reshapes documents to extract the Subject field from nested objects
  • $match: Filters out documents where Subject doesn't exist (empty objects)

Conclusion

The aggregation pipeline effectively filters documents with filled nested arrays by unwinding arrays, projecting nested fields, and matching only documents with existing values. This approach excludes empty nested objects from the results.

Updated on: 2026-03-15T01:41:07+05:30

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements