Background:
I have MongoDB replica sets running in Azure cloud service worker + web roles, using mongo-azure library. The first time I setup my Android
The reason for the intermittent errors is because of the default read preferences for the driver, mainly in regards to replica sets. The default read preference is primary. For each of the modes mentioned below, PRIMARY refers to the master database (always the most up-to-date) and SECONDARY refers to slave(s), which are basically the copies of master and are not always up-to-date.
PRIMARY: The default read mode. Read from primary only. Throw an error if
primary is unavailable. Cannot be combined with tags.
The solution to change the read preference to one of the following:
PRIMARY PREFERRED: Read from primary if available, otherwise a secondary.
SECONDARY PREFERRED: Read from a secondary if available, otherwise read from the primary.
NEAREST: Read from any member node from the set of nodes which respond the fastest.
Example code:
// Use this when doing a read if you don't care if the data is always consistent.
// Change the following with secondaryPreferred() if you have high writes, so
// that you don't interfere with them.
ReadPreference preference = ReadPreference.primaryPreferred();
DBCursor cur = new DBCursor(collection, query, null, preference);
For more info, see the source.