Issuing queries with primaryPreferred/secondaryPreferred read preferences immediately after MongoClient initialization can result in unintuitive behavior due to the MongoClient having an incomplete view of the cluster topology (e.g. primary not yet discovered; primary discovered but secondaries not yet discovered). We should update the read preference documentation to inform the user of this behavior.
ORIGINAL DESCRIPTION
Queries with readPreference as primaryPreferred are randomly distributed against primary and secondaries. As per the documentation under normal operations the reads should go against primary with readPreference as primaryPreferred.
Below are the profiling logs from secondary.
// rs0:SECONDARY> db.system.profile.findOne() rs0:SECONDARY> db.system.profile.findOne() { "op" : "query", "ns" : "sampledb.test", "command" : { "find" : "test", "filter" : { "customerId" : NumberLong(1041059) }, "lsid" : { "id" : UUID("8059690c-e554-4a3b-ae61-06363ffbd557") }, "$clusterTime" : { "clusterTime" : Timestamp(1621534366, 1), "signature" : { "hash" : BinData(0,"l+8rr0uUw0b/XCrtDXSML9+73m0="), "keyId" : NumberLong("6964250515110625281") } }, "$db" : "sampledb", "$readPreference" : { "mode" : "primaryPreferred" } }, "keysExamined" : 0, "docsExamined" : 51081, "cursorExhausted" : true, "numYield" : 399, "locks" : { "Global" : { "acquireCount" : { "r" : NumberLong(800) } }, "Database" : { "acquireCount" : { "r" : NumberLong(400) } }, "Collection" : { "acquireCount" : { "r" : NumberLong(400) } } }, "nreturned" : 0, "responseLength" : 211, "protocol" : "op_msg", "millis" : 91, "planSummary" : "COLLSCAN", "execStats" : { "stage" : "COLLSCAN", "filter" : { "customerId" : { "$eq" : NumberLong(1041059) } }, "nReturned" : 0, "executionTimeMillisEstimate" : 90, "works" : 51083, "advanced" : 0, "needTime" : 51082, "needYield" : 0, "saveState" : 399, "restoreState" : 399, "isEOF" : 1, "invalidates" : 0, "direction" : "forward", "docsExamined" : 51081 }, "ts" : ISODate("2021-05-20T18:12:52.463Z"), "client" : "xx.xx.xx.xxx", "allUsers" : [ { "user" : "*******", "db" : "admin" } ], "user" : "******@admin"}
Edit: Fixed code formatting.