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

237
Vistas
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

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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") }
]
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