6 / 6
Jan 2023

Hello,
I have a query like this

collection.aggregate( [ {"$match": {_id: 123}}, {"$project": {"attributes.key": 1, "attributes.value": 1}}, { "$project": { attributes: { "$filter": { input: "$attributes", as: "attr", cond: {"$in": ["$$attr.key", [1, 2, 3]]} } } } } ] )

And want to use replica to run this. I added {read: {mode: :secondary_preferred, max_staleness: 120}} as options. And now I’d like to check/confirm replica was used. I tried to run explain on the result but it doesn’t provide any information like that. Is there a way to check what was used to run aggregate query like this?

Hi @Alexey_Blinov,

Specifying a Read Preference of secondaryPreferred will cause the operation to target a secondary in most situations. When combined with a maxStalenessSeconds the operation will take replication lag (“staleness”) into consideration as well.

Per your example using the Ruby driver, assuming you (a) have a secondary member available and healthy and (b) that secondary is lagging behind the primary by less than 120 seconds, the operation should target that node.

And now I’d like to check/confirm replica was used.

Assuming the operation took longer than the slow query threshold (default 100ms) you could check the mongod logs for your secondaries to confirm which node ran the query.

I tried to run explain on the result but it doesn’t provide any information like that.

The explain results should contain a serverInfo field that would tell you which server ran the operation when it was explained. This doesn’t mean the operation prior to being explained ran on this server, but assuming you used the same read preference and max staleness settings it should allow you to rule out that the operation ran on the primary.

Thanks!
Yeah, I was expected to see serverInfo there. But saw only "queryPlanner" section. Hence my question.
I’ll try to run e few more explains. Maybe server info will be there.

16 days later

Ruby MongoDB driver’s explain do not accept options. It will show everything. And yeah, I was able to find info I need. Just have to call explain right after cursor was used. When I was checking something else and call explain after some time - output was modest.
Thank you

require('mongo') client = Mongo::Client.new('mongodb://mongo-0-a/test?readPreference=secondary') xs = client[:foo].find({"x":1}).explain(verbosity:'executionStats') puts JSON.pretty_generate(xs["serverInfo"])