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

119
Views
Count number of referenced objects in Mongo

Given two collections like:

users:
    name

posts:
    title
    user_id

How can I query for users with more than 5 posts efficiently?

I can do an aggregation with $lookup but that takes ages for large datasets.

Another option is to maintain a "postCount" on users but I would like to avoid having to maintain that.

I'm using Mongoose on Node.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

An efficient aggregate query which uses $lookup and a $redact pipeline for filtering would be as follows:

User.aggregate([
    {
        "$lookup": {
            "from": "posts",
            "localField": "_id",
            "foreignField": "user_id",
            "as": "posts"
        }
    },
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$size": "$posts" }, 5 ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
]).exec(function(err, results){
    if (err) throw err;
    console.log(results);
})
over 4 years ago · Santiago Trujillo 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!