Is it possible to exclude nested fields in MongoDB with a wildcard?

Yes, you can exclude nested fields with a wildcard pattern in MongoDB using the aggregation pipeline. This technique uses $objectToArray and $arrayToObject operators to transform nested objects, exclude specific fields, and reconstruct the document.

Syntax

db.collection.aggregate([
    { $project: { "nestedField": { $objectToArray: "$nestedField" } } },
    { $project: { "nestedField.v.fieldToExclude": 0 } },
    { $project: { "nestedField": { $arrayToObject: "$nestedField" } } }
]);

Sample Data

db.demo413.insertOne({
    "_id": "101",
    "details": {
        "Info1": {
            "Name": "Chris",
            "Age": 21
        },
        "Info2": {
            "Name": "David",
            "Age": 23
        }
    }
});
{ "acknowledged": true, "insertedId": "101" }

Display the current document ?

db.demo413.find();
{ "_id": "101", "details": { "Info1": { "Name": "Chris", "Age": 21 }, "Info2": { "Name": "David", "Age": 23 } } }

Example: Exclude Age Field from All Nested Objects

Remove the "Age" field from all nested objects within "details" ?

db.demo413.aggregate([
    { $project: { "details": { $objectToArray: "$details" } } },
    { $project: { "details.v.Age": 0 } },
    { $project: { "details": { $arrayToObject: "$details" } } }
]);
{ "_id": "101", "details": { "Info1": { "Name": "Chris" }, "Info2": { "Name": "David" } } }

How It Works

  1. Step 1: $objectToArray converts the nested object into an array of key-value pairs
  2. Step 2: Use projection to exclude the target field using dot notation on the "v" (value) property
  3. Step 3: $arrayToObject reconstructs the object from the modified array

Conclusion

Use the $objectToArray and $arrayToObject pipeline combination to exclude nested fields with wildcard behavior. This approach effectively removes the same field from all nested objects within a parent field.

Updated on: 2026-03-15T02:54:15+05:30

965 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements