1

I have a "Quiz" model, where each quiz document has some questions and an array of answers in them.

  1. 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"],
    },
 ]
  1. 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,
                    },
                },
            ])
  1. Output comes as:
[{
_id: "611478ac34dde61f28dbe4db",
questions: [
    {
       answers: ["a", "b", "c"],
    },
    {
       answers: ["m", "n", "o", "p"],
    },
 ]
}]
  1. 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
    },
 ]
}]

1 Answer 1

1

You can add new aggregation stage where you can use $map and $size pipeline operators, like this:

db.collection.aggregate([
  {
    $project: {
      "questions": {
        $map: {
          input: "$questions",
          as: "question",
          in: {
            answers: {
              $size: "$$question.answers"
            }
          }
        }
      }
    }
  }
])

Here is the working example: https://mongoplayground.net/p/0eyAlMWai0A

Sign up to request clarification or add additional context in comments.

1 Comment

Works! Appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.