Reputation: 169
I've collection named invoice, I wanted to sort my collection by date but result should be invoices having invoice number should be at top and invoice without having invoice number should be at the bottom.
I have tried this but not worked.
Invoice.find({},{sort:{createdAt :-1, invoiceNumber: 1}})
Upvotes: 0
Views: 126
Reputation: 606
Is not possible to do it just like that with a sort, as far as i know. You can try first sorting by invoiceNumber then by createdAt, but that wont give you the result you want.
For that I suggest you do 2 queries and then concat both of them into one array.
const withNumber = Invoice.find({ invoiceNumber: { $exists: true } }, { sort: { createdAt :-1 }});
const withoutNumber = Invoice.find({ invoiceNumber: { $exists: false } }, { sort: { createdAt :-1 }});
const all = [...withNumber, ...withoutNumber];
Upvotes: 1