Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda