Tushar Kale
Tushar Kale

Reputation: 169

Sort with multiple keys meteor mongodb

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

Answers (1)

Paulo Mogollón
Paulo Mogollón

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

Related Questions