1

I have a questions collection with _id and name and other fields(..), and a tests collection with _id, name and array of questions.

I'm trying to get all the questions with their fields and adding a field "usedIn" which counts the number of tests that the specific questions is present in.

 questions = await Question.aggregate([ /*{ "$match": { params } },*/ { "$lookup": { "from": "tests", "let": {"questionId": "$_id"}, pipeline: [ { "$match": { "$expr": { "$in": ["$$questionId", "$questions"], }, }, }, ], as: "tests" } }, { "$addFields": { "usedIn": { "$size": "tests" } } }, { "$project": fieldsObject }, ]) 

This code is giving me this error:

Error: Failed to optimize pipeline :: caused by :: The argument to $size must be an array, but was of type: string

What Am I doing wrong ?

1 Answer 1

1

You can do it like this:

db.questions.aggregate([ { "$lookup": { "from": "tests", "localField": "_id", "foreignField": "questions", "as": "usedIn" } }, { "$project": { "usedIn": { "$size": "$usedIn" }, "name": 1 } } ]) 

Working example

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.