How to make a MongoDB query sort on strings with -number postfix?

后端 未结 6 650
花落未央
花落未央 2021-01-04 01:04

I have a query:

ownUnnamedPages = Entries.find( { author : this.userId, title : {$regex: /^unnamed-/ }}, {sort: { title: 1 }}).fetch()

That

6条回答
  •  无人及你
    2021-01-04 01:13

    In mongo is not possible (sort strings in ascii) but you can sort with the below function after you get all documents from the collection

    const sortString = (a, b) => {
      const AA = a.title.split('-');
      const BB = b.title.split('-');
    
      if (parseInt(AA[1], 10) === parseInt(BB[1], 10)) {
        return 0;
      }
      return (parseInt(AA[1], 10) < parseInt(BB[1], 10)) ? -1 : 1;
    };
    
    document.sort(sortString);
    

提交回复
热议问题