Mongoid, how to order_by through a references_one association (and subsequent associations)? Mongoid, how to order_by through a references_one association (and subsequent associations)? mongodb mongodb

Mongoid, how to order_by through a references_one association (and subsequent associations)?


Dot notation is possible only for embedded documents, but you have 2 collections - houses and owners. In one of the Owner records in MongoDB you have only field house_id, in one of the House records you dont have any connection to Owner model.So the only way is to fetch all Houses and then to sort achieved collection using Enumerable#sort.


ways to do this would be:- embed the owner name as string in the house doc.The house object would have both a owner_id (so that you can fetch full owner doc) and an extra field with just the owner name as string.You only need to change the name when changing the owner_id and that can be done in 1 update so it is consistent.Using this it will be a very efficient query since it doesnt need to look across collections and docs for reads.Downside is a bit more mem used.

  • have the owner object reference the house, since the owner "owns".Then you can query owner sorted by name, then fetch the reference house documents that you will get in the correct order.This has the downside of doing many individual queries.

  • one extreme solution is to embed all those docs: hat inside owner, owner inside house.

best,AG