Querying/projecting embedded document field that has a period in its name

Learning MongoDB after many years in the SQL world.

Title says it all. I have a dataset that I have no control over, so I cannot rename any fields. One collection has documents that contain embedded documents. How can I include fields from the top-level document and a field from the embedded document where the field name contains on or more period?

For example, let’s say that the top-level document has fields named “cust_id”, “cust_name” and the embedded document (named “my_attributes”) contains a field named “this.right.here”. How can I project that field in the query results or within an aggregation pipeline?

The documentation has good examples for field names that begin with dollar signs, but nothing that I could replicate where a field name contains one or more period characters.

Hi, @Jeffrey_Dawson,
Assuming you’re using MongoDB version 5, you can use the $getField aggregation operator.
For example:

db.collection.aggregate([{
    $project: {
        field_name: {
            $getField: {
                field: 'this.right.here',
                input: '$my_attributes'
            }
        }
    }
}])

If you’re using version lower than 5.0 (but greater than or equal to 3.4.4), you can use this aggregation pipeline:

[{
    $project: {
        temp: {
            $first: {
                $filter: {
                    input: {
                        $objectToArray: '$my_attributes'
                    },
                    cond: {
                        k: 'this.right.here'
                    }
                }
            }
        }
    }
}, {
    $project: {
        val: '$temp.v'
    }
}]

Goodluck,
Rafael,