Skip to content

Commit 83a051c

Browse files
authored
MONGOID-5887 Include server hint for aggregate operations (#6035)
1 parent 08988f5 commit 83a051c

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

lib/mongoid/contextual/aggregable/mongo.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,12 @@ module Mongo
2727
# If no documents are found, then returned Hash will have
2828
# count, sum of 0 and max, min, avg of nil.
2929
def aggregates(field)
30-
result = collection.aggregate(pipeline(field), session: _session).to_a
30+
result = collection.aggregate(
31+
pipeline(field),
32+
session: _session,
33+
hint: view.hint
34+
).to_a
35+
3136
if result.empty?
3237
Aggregable::EMPTY_RESULT.dup
3338
else

spec/mongoid/contextual/aggregable/mongo_spec.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,39 @@
244244
end
245245
end
246246
end
247+
248+
context 'regarding hints' do
249+
let(:client) { Person.collection.client }
250+
let(:subscriber) { Mrss::EventSubscriber.new }
251+
252+
before do
253+
client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
254+
maybe_hint.aggregates(:age)
255+
end
256+
257+
after do
258+
client.unsubscribe(Mongo::Monitoring::COMMAND, subscriber)
259+
end
260+
261+
let(:event) { subscriber.single_command_started_event('aggregate') }
262+
let(:command) { event.command }
263+
264+
context 'when no hint is provided' do
265+
let(:maybe_hint) { Person }
266+
267+
it 'does not include the hint in the command' do
268+
expect(command['hint']).to be_nil
269+
end
270+
end
271+
272+
context 'when a hint is provided' do
273+
let(:maybe_hint) { Person.hint(age: 1) }
274+
275+
it 'includes the hint with the command' do
276+
expect(command['hint']).to eq({ 'age' => 1 })
277+
end
278+
end
279+
end
247280
end
248281

249282
describe "#avg" do

0 commit comments

Comments
 (0)