I'm facing an issue with grouping data in mongoDB and wondering if there's a way to transform an array into a string. The objects included in $lookup are currently displayed in an array format, but I need them in a single string.
Here is my code:
Answer.aggregate([
{$lookup:
{
from: "flashcards",
localField: "flashcard",
foreignField: "_id",
as: "flashcards"
}
},
{$lookup:
{
from: "flashcardcollections",
localField: "flashcards.collectionId",
foreignField: "_id",
as: "flashcardcollection"
}
},
{
$group: {
_id: { collectionName:"$flashcardcollection.name", isPublic: "$flashcardcollection.isPublic" },
Answers: {$sum: 1},
CorrectAnswers: { $sum: { $cond: [ { $eq: ["$isCorrect", true] }, 1, 0 ] } },
WrongAnswers: { $sum: { $cond: [ { $eq: ["$isCorrect", false] }, 1, 0 ] } },
ListOfAnswers: { $push: {date: "$date", isCorrect: "$isCorrect", prompt: "$flashcards.prompt"}}
}
},
], function (err, results) {
statisticsPerCollection.push(results)
console.log("statisticPerCollection:", JSON.stringify(statisticsPerCollection, null, 2))
})
}
The outcome:
[
{
"id": {
"collectionName": "MongoDBG",
"isPublic": true
},
"Answers": 11,
"CorrectAnswers": 8,
"WrongAnswers": 3,
"ListOfAnswers": [
{
"date": "2021-03-07T18:47:00.575Z",
"isCorrect": true,
"prompt": "MongoDbSize"
}
...
Desired result: "collectionName": "MongoDBG" instead of "collectionName": [ "MongoDBG" ]