Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda