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.
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 } }
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With