I have a Mongo collection that simply references an ID to another collection. Hypothetically the collection I’m specifically referring to might be called:
Walks. Walks has a reference to owner_id. The owner takes many walks with his many pets every day. What I want to do is query Walks for a list of N owner_ids and get only the last walk they took for each owner and group that by owner_id. To get a list of all walks by said list we’d do something like.
Walk.any_in(:owner_id => list_of_ids)
My question is, is there a way to query that list_of_ids, get only one walk per owner_id (the last one they took which can be sorted by the field created_at and returned in a hash where each walk is pointed to by an owner_id such as:
{ 5 => {..walk data..}, 10 => {.. walk data ..}}
Here’s an answer that uses MongoDB’s group command.
For the purposes of testing, I’ve used walk_time instead of created_at.
Hope that this helps and that you like it.
test/unit/walk_test.rb
test output