如何使用-number后缀对字符串进行MongoDB查询排序? [英] How to make a MongoDB query sort on strings with -number postfix?

查看:69
本文介绍了如何使用-number后缀对字符串进行MongoDB查询排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询:

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

返回以下数组:

[ { 
    title: 'unnamed-1',
    text: '<p>sdaasdasdasd</p>',
    tags: [],
    _id: 'Wkxxpapm8bbiq59ig',
    author: 'AHSwfYgeGmur9oHzu',
    visibility: 'public' },
{ 
    title: 'unnamed-10',
    text: '',
    author: 'AHSwfYgeGmur9oHzu',
    visibility: 'public',
    _id: 'aDSN2XFjQPh9HPu4c' },
{ 
    title: 'unnamed-2',
    text: '<p>kkhjk</p>',
    tags: [],
    _id: 'iM9FMCsyzehQvYGKj',
    author: 'AHSwfYgeGmur9oHzu',
    visibility: 'public' },
{ 
    title: 'unnamed-3',
    text: '',
    tags: [],
    _id: 'zK2w9MEQGnwsm3Cqh',
    author: 'AHSwfYgeGmur9oHzu',
    visibility: 'public' }]

问题是它似乎对第一个数字字符排序,所以它认为正确的顺序是1,10,2,3等....
我真正想要的是它排序在整个数字部分,以便10将在最后。

The problem is that it seems to sort on the first numeric character so it thinks the proper sequence is 1, 10, 2, 3, etc.... what I really want is for it to sort on both the whole numerical part so that 10 would be at the end.

我不希望通过为数字添加01或001等附加数字来做到这一点。

I'd prefer not to do this by having additional numbers such as 01 or 001 for the numbers.

我该怎么做?

推荐答案

MongoDB可以'按存储为字符串的数字排序。您必须将数字作为整数存储在其自己的字段中,使用前导零填充,或者在从数据库返回结果后对结果进行排序。

MongoDB can't sort by numbers stored as strings. You either have to store the number as an integer in its own field, pad with leading zeroes, or sort the results after they've been returned from the database.

这篇关于如何使用-number后缀对字符串进行MongoDB查询排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆