Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Null values last in MongoDB

I'm using the following query to populate items from MongoDB, in ascending order, according to a field called sortIndex.

Sometimes though items in the DB don't have the sortIndex field. With the following query, the items with a null sortIndex are showing up at the top, and I'm wondering how to get them to show up at the bottom. Would I need two queries for this or is there a way to use one query?

.populate({path: 'slides', options: { sort: { 'sortIndex': 'ascending' } } })
like image 252
Ben Davidow Avatar asked Dec 15 '16 00:12

Ben Davidow


2 Answers

You can do something like this:

db.collection.aggregate([
    { $addFields: 
        { 
            hasValue : { $cond: [ { $eq: [ "$value", null ] }, 2, 1 ] },
        }
    },
])
.sort({hasValue : 1, value : 1});
like image 109
Yogesh Barot Avatar answered Oct 17 '22 01:10

Yogesh Barot


Duplicate of: How to keep null values at the end of sorting in Mongoose?

Anyway posting the same solution ...

Am not sure about the solution am about to say. I cant test this out as I dont have a mongo db set right now, but I think that you can use <collection>.aggregate along with $project and $sort to achieve this.

Sample code:

db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            description: { $ifNull: [ "$amount", -1*(<mimimum value>)* ] }
         }
      },
      { 
         $sort : { 
           amount : (-1 or 1 depending on the order you want)
         }
      }
   ]
)

Hope this helps !!

like image 35
vizsatiz Avatar answered Oct 17 '22 01:10

vizsatiz