Ben Davidow
Ben Davidow

Reputation: 1215

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' } } })

Upvotes: 7

Views: 7074

Answers (2)

Yogesh Barot
Yogesh Barot

Reputation: 131

You can do something like this:

db.collection.aggregate([
    { $addFields: 
        { 
            hasValue : { $cond: [ { $eq: [ "$value", null ] }, 2, 1 ] },
        }
    },
])
.sort({hasValue : 1, value : 1});

Upvotes: 9

vizsatiz
vizsatiz

Reputation: 2173

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 !!

Upvotes: 3

Related Questions