mongodbaggregateremap

MondoDB aggregation - remapping inner documents


How could I remap inner documents like this in the following example:

db.customers.aggregate(
[
    {
        $project: {
            "_id": 0,
            "First Name": "customerDetails.firstName",
            "Last Name": "customerDetails.lastName",
            "Full Name": { $concat : [ "customerDetails.firstName", " ", "customerDetails.lastName" ] }
        }
    }
]

)

Placing the $ like this "$customer.firstName" doesn't work and instead of taking the value of the inner field firstName basically it doesn't return anything.

Example of the structure of customer collection:

{
    "_id" : ObjectId("5fb3c41454742e0d3c9f7605"),
    "customerDetails" : {
        "firstName" : "Robert",
        "lastName" : "Green",
        "phoneNumber" : "0878712375",
        "email" : "robert.green@gmail.com"
    }
}

Expected result:

{
    "First Name": "Robert",
    "Last Name": "Green",
    "Full Name": "Robert Green"
}

Actual result:

{
    "First Name": "customerDetails.firstName",
    "Last Name": "customerDetails.lastName",
    "Full Name": "customerDetails.firstName customerDetails.lastName"
}

Solution

  • Reference the fields with $, should work:

    db.customers.aggregate(
    [
        {
            $project: {
                "_id": 0,
                "First Name": "$customerDetails.firstName",
                "Last Name": "$customerDetails.lastName",
                "Full Name": { $concat : [ "$customerDetails.firstName", " ", "$customerDetails.lastName" ] }
            }
        }
    ]