简体   繁体   中英

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

You can do something like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM