I am struggling with grouping data in mongoDB and I would like to know if there is any way to convert an array into a string? Unfortunately, the objects that were included in $lookup are displayed in the array instead of a single string.
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 result:
[
{
"_id": {
"collectionName": [
"MongoDBG"
],
"isPublic": [
true
]
},
"Answers": 11,
"CorrectAnswers": 8,
"WrongAnswers": 3,
"ListOfAnswers": [
{
"date": "2021-03-07T18:47:00.575Z",
"isCorrect": true,
"prompt": [
"MongoDbSize"
...
expectations: "collectionName": "MongoDBG" instead of "collectionName": [ "MongoDBG" ]