MongoDB query to find records with keys containing dots?

To find MongoDB records containing field names with dots, use the aggregation pipeline with $addFields, $objectToArray, and $filter operators. The $indexOfBytes operator detects dot characters in field names.

Syntax

db.collection.aggregate([
    {
        $addFields: {
            result: {
                $filter: {
                    input: { $objectToArray: "$fieldName" },
                    cond: {
                        $ne: [ { $indexOfBytes: [ "$$this.k", "." ] }, -1 ]
                    }
                }
            }
        }
    },
    {
        $match: {
            $expr: {
                $ne: [ { $size: "$result" }, 0 ]
            }
        }
    },
    {
        $project: {
            result: 0
        }
    }
]);

Sample Data

db.demo364.insertMany([
    {
        "details": {
            "details1.otherdetails.Name": {"FirstName": "Chris"}
        }
    },
    {
        "details": {
            "details1.otherdetails.Name": {"FirstName": "David"}
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e57d485d0ada61456dc936d"),
        ObjectId("5e57d486d0ada61456dc936e")
    ]
}

Example

Find all documents where field names contain dots ?

db.demo364.aggregate([
    {
        $addFields: {
            result: {
                $filter: {
                    input: { $objectToArray: "$details" },
                    cond: {
                        $ne: [ { $indexOfBytes: [ "$$this.k", "." ] }, -1 ]
                    }
                }
            }
        }
    },
    {
        $match: {
            $expr: {
                $ne: [ { $size: "$result" }, 0 ]
            }
        }
    },
    {
        $project: {
            result: 0
        }
    }
]);
{ "_id": ObjectId("5e57d485d0ada61456dc936d"), "details": { "details1.otherdetails.Name": { "FirstName": "Chris" } } }
{ "_id": ObjectId("5e57d486d0ada61456dc936e"), "details": { "details1.otherdetails.Name": { "FirstName": "David" } } }

How It Works

  • $objectToArray converts the object into key-value pairs
  • $indexOfBytes searches for dot character in each key name
  • $filter keeps only keys containing dots (where index ? -1)
  • $match returns documents with at least one matching key
  • $project removes the temporary result field

Conclusion

Use aggregation pipeline with $objectToArray and $indexOfBytes to identify MongoDB documents containing field names with dots. This approach efficiently filters records based on field name patterns.

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

890 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements