I have a mongodb replica set of 3 nodes, with the primary and one secondary located in the US, and another secondary in Western Europe. I'd like my nodejs application to read from whichever replica is nearest. I'm using the following connection URI to do this:


However, the application always ends up reading from the primary node in the set. Almost all of the queries are aggregations and I'm not doing any writes at all. All of the nodes in the replica are healthy and reachable according to rs.status().

I've also tried using readPreferences of 'secondary' and 'secondaryPreferred' but all have shown the same behaviour.

Am I missing something here?

  • What are your versions of MongoDB Node driver and server? How are you confirming the application always reads from the primary? Have you tried creating a minimal test script for read prefs? The nearest read preference is based on network latency so may return a primary or a secondary. A secondary read preference always returns a secondary, so if that isn't working for your test case the read preference must not be set correctly. Does your secondary in Western Europe have any non-default options in the replica set config? – Stennie Apr 27 '18 at 22:09
  • @Stennie After creating a minimal test script I can see that both nearest and secondary readPrefs are working as expected for find() queries (i.e. using either secondary or the EU replica), but aggregation pipeline queries are being run on the primary with an identical connection URI. Is this expected functionality? Thanks for your help. – bakerg Apr 30 '18 at 9:12
  • What are your specific versions of MongoDB Node driver and MongoDB server? What stages and options does your aggregation query include? Are you aggregating against a collection or a view? As long as your aggregation doesn't include a stage which needs to write data (for example, $out), it is expected that your read preferences would be respected. Versions would be very helpful to determine if this might be a known issue (or to try to reproduce the problem). – Stennie Apr 30 '18 at 13:09
  • @Stennie driver version 3.0.7, server version 3.6.4. Aggregations are all on collections. Majority of pipelines are made of $geoNear, $match, $group, $unwind, $facet, $count, and $project stages. No $out stages or any others I'd expect to write. – bakerg Apr 30 '18 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.