benedikt/mongoid-tree — pull request #39 by benhutton (2013-07-05 19:57:35+00:00)
Title: Reordering nodes can cause #ancestor to give results out of order

Here's some sample output.

This is the order that my parent ids are stored in the array:

irb(main):018:0> page.parent_ids
=> ["515c547c392d4ecdf6000004", "515c5732392d4ecdf600003a", "51d1f63fd268d9289600037c", "515c5740392d4ecdf60000f1"]

This is the order that they are returned by #ancestors:

irb(main):004:0> page.ancestors.map(&:id)
=> ["515c547c392d4ecdf6000004", "515c5732392d4ecdf600003a", "515c5740392d4ecdf60000f1", "51d1f63fd268d9289600037c"]

You'll notice the last 2 are flipped.

It seems that when no sort order is specified, MongoDB returns documents based on the order that they are stored in the disk: http://docs.mongodb.org/manual/reference/glossary/#term-natural-order

It seems to me that the least computationally expensive way to do this is to add a depth field, which may come in handy other places as well. I'm not very experienced with mongodb, so if anyone has a better suggestion I'm very open to it.