Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid order_by with multiple fields resulting unexpected

I have followed two.mongoid.org doc, seems something is off with order_by on multiple fields.

I am having a Link model with title and link_order fields, and first I want to sort records by link_order than created_at.

but not getting expected result:

I am expecting this order ['e', 'a', 'b', 'c', 'd']

---------------
title | link_order
---------------
a     | 0
b     | 0
c     | 0
d     | 0
e     | 1
---------------

Link.order_by([[:created_at, :asc]]).collect(&:title)
['a', 'b', 'c', 'd', 'e']

Link.order_by([[:link_order, :desc], [:created_at, :asc]]).collect(&:title)
['e', 'd', 'c', 'b', 'a']

like image 523
Raghvendra Parashar Avatar asked Dec 20 '25 12:12

Raghvendra Parashar


1 Answers

In MongoDB as _id is created by timestamp only. You can try below query and I think it should work fine

 Link.order_by(:link_order.desc,:_id.asc).collect(&:title)
like image 101
abhas Avatar answered Dec 23 '25 21:12

abhas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!