How to make $ concat fields in an array of objects?

What i have

I have the following documents included in my aggregation pipeline:

[
    { 
        "email" : "email@example.com", 
        "name"  : "Organization Name",  
        "users" : [
            {
                "lastName"  : "Nye", 
                "firstName" : "Bill", 
                "email"     : "bnye@example.com"
            },
            {
                "lastName"  : "Rogers", 
                "firstName" : "Mr.", 
                "email"     : "mrrogers@example.com"
            }
        ]
    },
    ...
]

What I want

Usage $projectI want $concatfields firstNameand lastNamein each of the subdocuments of the array I get the following result:

{ 
    "email" : "email@example.com", 
    "name"  : "Organization Name",  
    "users" : [
        {
            "name"  : "Bill Nye", 
            "email" : "bnye@example.com"
        },
        {
            "name"  : "Mr. Rogers", 
            "email" : "mrrogers@example.com"
        }
    ]
}

What I tried - Attempt # 1

I tried the following aggregation:

db.organizations.aggregate([
    {
        $project: {
            email : 1,
            name  : 1,
            users : {
              name  : { $concat : [ "$users.firstName", " ", "$users.lastName" ] },
              email : 1
            }
        }
    }
]);

... but I get the following error:

$ concat only supports strings, not Array

What I tried - Attempt No. 2

I also tried the following aggregation:

db.organizations.aggregate([
    {
        $project: {
            email : 1,
            name  : 1,
            users : {
              name  : { $concat : [ "$firstName", " ", "$lastName" ] },
              email : 1
            }
        }
    }
]);

... but namealways returns null.

It seems to me that this should be a relatively simple task, however, I am completely at a dead end.

How to get the results I'm looking for?

+4
source share
1

$project $map, $concat .

db.organizations.aggregate(
    [
        { "$project": { 
            "email": 1, 
            "name": 1, 
            "users": { 
                "$map": { 
                    "input": "$users", 
                    "as": "u", 
                      "in": { 
                          "name": { "$concat" : [ "$$u.firstName", " ", "$$u.lastName" ] }, 
                          "email": "$$u.email" 
                      } 
                }
            } 
        }} 
    ]
)
+7

All Articles