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

223
Visualizações
Sorting without considering null values

In js with node js i want to sort result from model without considering document with nil values for example Products = [ {_id:ObjectID(), priority:3},

{_id:ObjectID(), priority:1},

{_id:ObjectID(), priority:2},

{_id:ObjectID()} ]

So this mongo schema so i need a query to find sorted element witjout considering nil but documemts with nil values must be at the end of results in both ascending or deacending order

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

0

So here is an example assuming your data is in a collection called "products". Here we assume the null value is expected to sort at the end of the results. Also, it is assumed you wish to sort priority in an ascending fashion.

I use an arbitrary large number - 999999 - to represent null values and sort by that value.

Aggregation

db.products.aggregate([
    {
        $addFields:
        {
            "sortField":
            {
                $ifNull: [ "$priority", 9999999 ]
            }
        }
    },
    {
        $sort: { "sortField": 1 }
    },
    {
        $project: { "sortField": 0 }
    }
])

Results

[
  { _id: ObjectId("61b0e373c6c466d7d1ea9b5b"), priority: 1 },
  { _id: ObjectId("61b0e373c6c466d7d1ea9b5c"), priority: 2 },
  { _id: ObjectId("61b0e373c6c466d7d1ea9b5a"), priority: 3 },
  { _id: ObjectId("61b0e373c6c466d7d1ea9b5d") }
]
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