Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
Mongoose Lookup with foreign key as array

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 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!