mongoid/mongoid — Issue #1548: HABTM relations return docs in the wrong order
Author: nickhoffman
Created: 2012-01-03 23:06:12+00:00
State: open
Labels: bug, confirmed

If you have a HABTM relation, Mongoid retrieves the related documents in the wrong order.

This is because the _$in_ operator is used, which causes the related documents to be sorted by using [MongoDB's natural order](http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order) .

I'd expect the documents to be returned in the order that their IDs are stored in.

This was originally reported in #246, and fixed in rc.1 , but seems to have regressed since then.

Here's an example that shows the bug:

```ruby
class Post
include Mongoid::Document

has_and_belongs_to_many :tags
end

class Tag
include Mongoid::Document

field :name, :type => String

has_and_belongs_to_many :posts
end

Post.delete_all
Tag.delete_all

t1 = Tag.create :name => 'T1'
t2 = Tag.create :name => 'T2'
t3 = Tag.create :name => 'T3'
t4 = Tag.create :name => 'T4'

p = Post.create :tag_ids => [t2.id, t4.id, t1.id, t3.id]
p.reload

# The tags' order in the "tag_ids" field:
p.tag_ids.map {|id| Tag.find(id).name}
=> ["T2", "T4", "T1", "T3"]

# The tags' order from the "tags" relation:
p.tags.map(&:name)
=> ["T1", "T2", "T3", "T4"]
```