简体   繁体   中英

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

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];

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