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

186
Vistas
How To Query Unique Users With Mongoose

Context
In a MongoDB database, I have a collection with mail documents inside. Each document has receiver and sender fields.

Goal
I want to query for one mail from each sender. In other words, I do not want two or more mail from the same sender.

Example
I have three documents:

{
    _id: 1,
    sender: John,
    receiver: Kate
}

{
    _id: 2,
    sender: John,
    receiver: Kate
}

{
    _id: 3,
    sender: Mike,
    receiver: Kate
}

After the query, I should end up with: (the second mail from John is not included)

{
    _id: 1,
    sender: John,
    receiver: Kate
}

{
    _id: 3,
    sender: Mike,
    receiver: Kate
}

Please help! Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

use this aggregation, group by sender and push receiver to array then put receiver as first element of array

db.collection.aggregate([
  {
    $group: {
      _id: {
        "sender": "$sender"
      },
      r: {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$project": {
      sender: "$_id.sender",
      receiver: {
        $first: "$r.receiver"
      },
      description: {
        $first: "$r.description"
      },
      _id: 0
    }
  }
])

https://mongoplayground.net/p/mwDdL4aLneu

about 4 years ago · Juan Pablo Isaza 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