Home > Software design >  Sorting without considering null values
Sorting without considering null values

Time:12-09

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

CodePudding user response:

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