简体   繁体   中英

How to sort in mongoDb using gem 'mongo' with Ruby (Sinatra)?

I NUMBERED THE SORTING SHOWS IN RED BOX :

在此处输入图片说明

I have the following codes, but I failed to sort the data fetched from MongoDb.

display_order = field in DB

MongoConnect = Mongo::Client.new(127.0.0.1:27017, :database => 'my_db')

MongoConnect[:clients].find(:year => '2015').sort({month: 1})

I searched that sort function has ONLY 2 possible value:

1 is Ascending

-1 is Descending

It seems correct because I tried to put like ' asc/desc ' or ' ascending/descending ' value, and I got error as Invalid value for sort.

As you can see in the screenshot, the sorting is not properly done. It sorts the data, by getting first all with 1 .

BUT I want to sort it in ASCENDING order.

Is it due to STRING data? If YES how can I fix it?

Please help!

If your fields contain strings they will be sorted as such. If you want them to be sorted as integers then you must store them as integers.

My mistake , I thought before I cannot use unqouted value when creating records since I'm using mongo-express as GUI .

My first way when adding value to month field:

{
    "_id": ObjectID(""),
    "year": "2015",
    "month": "1",
    "value": "90"
}

I thought, the value should always be quoted .

Now, my function for sorting is working. Just removing the qoutes as setting value to month field.

As shown below:

{
    "_id": ObjectID(""),
    "year": "2015",
    "month": 1,
    "value": "90"
}

I hope this will help others, and don't do the same mistake I made :D

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