convert array to string in $project (aggregate)

Viewed 2062

i use $project operation to specify the inclusion of fields i have this code:

[{
    '$lookup': {
        'from': 'users',
        'localField': 'owner',
        'foreignField': 'id'
        'as': 'user'
    }
}, {
    '$project': {
        'userName': '$user.username',
        'userId': '$user.id'
    }
}]

i have the result below:

[
    {
        "userName": [
            "jscode"
        ],
        "userId": [
            "5d1888d60c627764aabd8b1e"
        ]
    }
]

i need to convert userId and userName results from array to string like this:

[
    {
        "userName": "jscode" ,
        "userId": "5d1888d60c627764aabd8b1e"
    }
]

thanks :)

1 Answers

You can use below $project stage

{
  "$project": {
    "userName": { "$arrayElemAt": ["$user.username", 0] },
    "userId": { "$arrayElemAt": ["$user.id", 0] }
  }
}

Or Using $unwind

[
  { "$lookup": {
    "from": "users",
    "localField": "owner",
    "foreignField": "id",
    "as": "user"
  }},
  { "$unwind": "$user" },
  { "$project": {
    "userName": "$user.username",
    "userId": "$user.id"
  }}
]

Actually $lookup always returns the new field in form of array. So to pick the field from that array you either need to use $unwind or can $arrayElemAt to pick the 0th element.

Related