This question already has an answer here:
- How can I sort into that nulls are last ordered in mongodb? 1 answer
I am querying a collection and sorting results based on a property. Some documents don't the that property value yet i.e. null. I want to keep the documents with null values at the end of the results after sorting and limiting (asc or desc). Is there a simple way in Mongoose to do that using a single query? If not, how can I use two queries separately since I have to limit the results as well for pagination?
var dealSchema = new Schema({
// For Presentation Purposes Only
dealId: { type: Number, index: true, unique: true },
// BRAND Info
brand: { type: ObjectId, ref: 'brand', index: true },
brandUser: { type: ObjectId, ref: 'user', index: true, required: true },
campaign: { type: ObjectId, ref: 'campaign', index: true },
metrics: {
totalCost: Number,
totalValue: Number,
roi: { type: Number, index: true },
cpe: { type: Number, index: true }
}
})
I want to sort based on 'metrics.cpe' in ascending order, but want null or 0 values to be at the end of the list. Example:
[0.1, 0.4, 0.7, 1.5, 2.5, 0, 0, null, null]
Sample document
{
"_id": "590cdf29c102ae31208fa43a",
"campaign": "587e6a880c844c6c2ea01563",
"brand": "5a4cff5f8eaa1c26ca194acc",
"brandUser": "57fd30cf0df04f1100153e07",
"metrics": {
"roi": 0,
"cpe": 0,
"totalValue": 0,
"totalCost": 6000
}
}