Using mongodb, I would like to transform an array in a a document that looks like this:
{activities: [{"start": start_date, "end": end_date, value:"4332A"}]}
Into an object, like this (only projecting the value field as the value of "activities"):
{activities: "4332A"}
I have tried using $arrayToObject in the $project stage, but the results is not really what I am looking for :
db.companies.aggregate([{
$project: {
$map: {
'input': '$activities',
'as': 'item',
'in': {
'k': 'activities',
'v': '$$item.value'
}
}
}
])
The output being:
{"activities": {"activities": "4332A"}}
CodePudding user response:
Assuming there is always exactly one result in the array ( as you said ), you can just use arrayElemAt, like so:
db.collection.aggregate([
{
$addFields: {
activities: {
"$arrayElemAt": [
"$activities.value",
0
]
}
}
}
])