I am trying to project two elements of an array I got after joining two documents using $lookup. When I use the dot notation to access the array elements as below -
db.departments.aggregate([{
$lookup: {
from: 'employees',
localField: 'dep_id',
foreignField: 'department',
as: 'emps'
}
}, {
$project: {
_id: 0,
emp_id: 1,
salary: 1,
emp_name: '$emps.name',
username: '$emps.username'
}
}])
I get the following result -
emp_id:910579
salary:100000
emp_name:Array
0:"Stephen Wolf"
username:Array
0:"StepWolf"
I want the result as follows -
emp_id:910579
salary:100000
emp_name:"Stephen Wolf"
username:"StepWolf"
Does anybody have any suggestions? I want something that can convert array element to attribute, similar to the ObjectToArray function.
CodePudding user response:
Query1
- the bellow does
field : [m1 m2 m2]
=>field : m1
- takes the first member and makes it the value of the field
aggregate(
[{"$set":
{"emp_name": {"$arrayElemAt": ["$emp_name", 0]},
"username": {"$arrayElemAt": ["$username", 0]}}}])
Query2
- If you have MongoDB >=5 you can use
$first
also
aggregate(
[{"$set":
{"emp_name": {"$first": "$emp_name"},
"username": {"$first": "$username"}}}])
In your case use query1 or query2 inside the project you already have, like :
{
$project: {
_id: 0,
emp_id: 1,
salary: 1,
"emp_name": {"$first": "$emp_name"},
"username": {"$first": "$username"}
}
}