I have a "Quiz" model, where each quiz document has some questions and an array of answers in them.
- Example document structure (Quiz.findOne()):
_id: ObjectId("611478ac34dde61f28dbe4db"),
name: "Quiz 1",
questions: [
{
text: "Question 1",
answers: ["a", "b", "c"],
},
{
text: "Question 2",
answers: ["m", "n", "o", "p"],
},
...
...
{
text: "Question 1000",
answer: ["a", "c", "e", "f"],
},
]
- I am selecting some particular questions by index, using MongoDB aggregation.
Aggregation code:
Quiz.aggregate([
{
$match: { _id: "611478ac34dde61f28dbe4db" },
},
{
$addFields: {
questions: {
$map: {
input: [0, 1], //Choosing the questions at index 0 and 1 (can be any other index)
as: "i",
in: {
$arrayElemAt: ["$questions", "$$i"],
},
},
},
},
},
{
$project: {
"questions.answers": 1,
},
},
])
- Output comes as:
[{
_id: "611478ac34dde61f28dbe4db",
questions: [
{
answers: ["a", "b", "c"],
},
{
answers: ["m", "n", "o", "p"],
},
]
}]
- How can I convert this output to show only the "$size" of the array?
Expected output:
[{
_id: "611478ac34dde61f28dbe4db",
questions: [
{
answers: 3, //Had 3 answers: a, b, c
},
{
answers: 4, //Had 4 answers: m, n, o, p
},
]
}]