Raghvendra Parashar
Raghvendra Parashar

Reputation: 4053

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

Upvotes: 3

Views: 2346

Answers (1)

abhas
abhas

Reputation: 5213

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)

Upvotes: 4

Related Questions