How to set read preference in aggregation pipeline?

result = User.collection.aggregate(pipeline,{:read => {:mode => :secondary}})
this is not working.

Hi @Vishwajeet_Thoke,

Based on the example you shared I’m assuming you’re trying to change the Read Preference for this operation using the Mongoid ODM.

Note that result in your example will only hold a Mongo::Collection::View::Aggregation; not the result. By calling to_a the command will be executed and the desired result will be retrieved using your selected read preference.

The following example should count the total users and target a secondary:

User.collection.aggregate([{ '$count' => 'total' }], read: { mode: :secondary }).to_a