Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort documents in mongodb so that null values appear last

Let's say my mongo document looks like this:

{
  _id: "some _id",
  name: "some name",
  type: "A" | "B" | "C" | or it may be null
}

When I call db.getCollection('mycollection').find().sort({ type: -1 }) I'm getting documents with type: null first because the data is sorted by canonical type where null has much lower canonical value than that of number/string

Is there a way to form a query, so that null values would appear last?

I have found this question How can I sort into that nulls are last ordered in mongodb? but there it's suggested to use aggregation and add "fake" values which does not seem good to me.

Using aggregation may work if forming a facet with sorted documents where sorting criteria is not null and documents where it is null and then concatinating both arrays, but that can get complicated when there're more than one sorting criteria.

like image 636
Le garcon Avatar asked Sep 13 '25 00:09

Le garcon


1 Answers

You can use $type operator to get a type of field (null or string) and then $sort by field type plus then by your field, try:

db.col.aggregate([
    { $addFields: { fieldType: { $type: "$type" } } },
    { $sort: { fieldType: -1, type: 1 } },
    { $project: { "fieldType": 0 } }
])
like image 55
mickl Avatar answered Sep 15 '25 14:09

mickl