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

167
Visualizações
How to get key that has max value inside a nested object in MongoDB collection?

Consider the below MongoDB collection

[
    {
        _id: 123,
        links: {
            "google.com": 3,
            "facebook.com": 4,
            "whatsapp.com": 6
        }
    },
    {
        _id: 123,
        links: {
            "google.com": 4,
            "facebook.com": 6,
            "yahoo.com": 8
        }
    },
    {
        _id: 123,
        links: {
            "mail.com": 3,
            "twitter.com": 4,
            "whatsapp.com": 5
        }
    }
]

Let's say the above documents are in the mongodb collection and I want to retrive the max link that has the more number.
For example:

  • "google.com" has 7 as sum
  • "facebook.com" has 10 as sum
  • "whatsapp.com" has 11 as sum
  • "yahoo.com" has 10
  • "mail.com" has 3
  • "twitter.com" has 4

So here the highest number is for key "whatsapp.com" I need this key and total sum 11
Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  • $objectToArray convert links object to key-value format array of object
  • $unwind to deconstruct the links array
  • $group by links name and count total value
  • $sort by total value in descending order
  • $limit 1 to select single document
db.collection.aggregate([
  { $addFields: { links: { $objectToArray: "$links" } } },
  { $unwind: "$links" },
  {
    $group: {
      _id: "$links.k",
      count: { $sum: "$links.v" }
    }
  },
  { $sort: { count: -1 } },
  { $limit: 1 }
])

Playground

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