diff --git a/lib/mongoid/contextual/aggregable/mongo.rb b/lib/mongoid/contextual/aggregable/mongo.rb index a7972ae0a2..9a92fe8325 100644 --- a/lib/mongoid/contextual/aggregable/mongo.rb +++ b/lib/mongoid/contextual/aggregable/mongo.rb @@ -27,7 +27,12 @@ module Mongo # If no documents are found, then returned Hash will have # count, sum of 0 and max, min, avg of nil. def aggregates(field) - result = collection.aggregate(pipeline(field), session: _session).to_a + result = collection.aggregate( + pipeline(field), + session: _session, + hint: view.hint + ).to_a + if result.empty? Aggregable::EMPTY_RESULT.dup else diff --git a/spec/mongoid/contextual/aggregable/mongo_spec.rb b/spec/mongoid/contextual/aggregable/mongo_spec.rb index 307b708c28..74f7166cbe 100644 --- a/spec/mongoid/contextual/aggregable/mongo_spec.rb +++ b/spec/mongoid/contextual/aggregable/mongo_spec.rb @@ -244,6 +244,39 @@ end end end + + context 'regarding hints' do + let(:client) { Person.collection.client } + let(:subscriber) { Mrss::EventSubscriber.new } + + before do + client.subscribe(Mongo::Monitoring::COMMAND, subscriber) + maybe_hint.aggregates(:age) + end + + after do + client.unsubscribe(Mongo::Monitoring::COMMAND, subscriber) + end + + let(:event) { subscriber.single_command_started_event('aggregate') } + let(:command) { event.command } + + context 'when no hint is provided' do + let(:maybe_hint) { Person } + + it 'does not include the hint in the command' do + expect(command['hint']).to be_nil + end + end + + context 'when a hint is provided' do + let(:maybe_hint) { Person.hint(age: 1) } + + it 'includes the hint with the command' do + expect(command['hint']).to eq({ 'age' => 1 }) + end + end + end end describe "#avg" do