Changing the output of an aggregation query where the key is the field name from the database.
I tried the following: How to use field value as key name in Mongodb result
But it results in the following error:
MongoError: $arrayToObject requires an object keys of 'k' and 'v'. Found incorrect number of keys:1
var data = await Message.aggregate([
{
$group: {
_id: '$message',
last_message: { $last: '$date_create', },
conversation: {
$push: '$$ROOT',
},
},
},
{
$project: {
input: { $arrayElemAt: ['$conversation.message', 0] },
output: { $arrayElemAt: ['$conversation.mainTopic', 0] },
_id: 0,
},
},
{ $sort: { last_message: -1 } },
]);
I want to change the ouput from (current result):
{ "input": "Test", "output": "general" },
TO:
{ "input": "Test", "output": { general: 1, }, },