Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7980203
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T09:59:43+00:00 2026-06-04T09:59:43+00:00

I have a Mongo collection that simply references an ID to another collection. Hypothetically

  • 0

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 ..}}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T09:59:44+00:00Added an answer on June 4, 2026 at 9:59 am

    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.

    class Owner
      include Mongoid::Document
      field :name, type: String
      has_many :walks
    end
    
    class Walk
      include Mongoid::Document
      field :pet_name, type: String
      field :walk_time, type: Time
      belongs_to :owner
    end
    

    test/unit/walk_test.rb

    require 'test_helper'
    
    class WalkTest < ActiveSupport::TestCase
      def setup
        Owner.delete_all
        Walk.delete_all
      end
    
      test "group in Ruby" do
        walks_input = {
            'George' => [ ['Fido',  2.days.ago], ['Fifi',  1.day.ago],  ['Fozzy',    3.days.ago] ],
            'Helen'  => [ ['Gerty', 4.days.ago], ['Gilly', 2.days.ago], ['Garfield', 3.days.ago] ],
            'Ivan'   => [ ['Happy', 2.days.ago], ['Harry', 6.days.ago], ['Hipster',  4.days.ago] ]
        }
        owners = walks_input.map do |owner_name, pet_walks|
          owner = Owner.create(name: owner_name)
          pet_walks.each do |pet_name, time|
            owner.walks << Walk.create(pet_name: pet_name, walk_time: time)
          end
          owner
        end
        assert_equal(3, Owner.count)
        assert_equal(9, Walk.count)
        condition = { owner_id: { '$in' => owners[0..1].map(&:id) } } # don't use all owners for testing
        reduce = <<-EOS
          function(doc, out) {
            if (out.last_walk == undefined || out.last_walk.walk_time < doc.walk_time)
              out.last_walk = doc;
          }
        EOS
        last_walk_via_group = Walk.collection.group(key: :owner_id, cond: condition, initial: {}, reduce: reduce)
        p last_walk_via_group.collect{|r|[Owner.find(r['owner_id']).name, r['last_walk']['pet_name']]}
        last_walk = last_walk_via_group.collect{|r|Walk.new(r['last_walk'])}
        p last_walk
      end
    end
    

    test output

    Run options: --name=test_group_in_Ruby
    
    # Running tests:
    
    [["George", "Fifi"], ["Helen", "Gilly"]]
    [#<Walk _id: 4fbfa7a97f11ba53b3000003, _type: nil, pet_name: "Fifi", walk_time: 2012-05-24 15:39:21 UTC, owner_id: BSON::ObjectId('4fbfa7a97f11ba53b3000001')>, #<Walk _id: 4fbfa7a97f11ba53b3000007, _type: nil, pet_name: "Gilly", walk_time: 2012-05-23 15:39:21 UTC, owner_id: BSON::ObjectId('4fbfa7a97f11ba53b3000005')>]
    .
    
    Finished tests in 0.051868s, 19.2797 tests/s, 38.5594 assertions/s.
    
    1 tests, 2 assertions, 0 failures, 0 errors, 0 skips
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Mongo collection called documents which has the following structure: { name:
I have a mongo collection which has documents with two fields fieldA and fieldB,
We have a mongo collection that can be search&sorted on many fields. For example
I have a Mongo collection where each document has a set of unique embedded
I have many collections of documents in a mongo database that look like this:
In Mongo my understanding is that you can have databases and collections. I'm working
I have a database connection that I got like this: db = Mongo::Connection.new.db(app-development) but
I have a collection in mongo in which I am inserting data from Perl
I have an existing mongo database where all documents in a collection have a
Just started mongo and started having issue with querying already. i have a collection

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.