This error occurs when your application tries to write to a secondary node instead of the primary in a MongoDB replica set. Write operations are only allowed on the primary node to maintain data consistency.
MongoDB Error Code 10107 (NotWritablePrimary) indicates that a write operation was attempted on a node that is not the primary replica set member. In MongoDB replica sets, only the primary node accepts write operations. Secondary nodes are read-only to prevent data inconsistency. This error commonly occurs when the client connection string points to a secondary node, or when the primary has failed and the client hasn't updated its connection to the newly elected primary during failover.
Check your MongoDB connection string to ensure it connects to the replica set name, not individual nodes. Use the correct format:
mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=rs0Avoid connecting directly to a single node:
// Bad - connects to secondary
mongodb://secondary-node:27017Good - connects to replica set and automatically finds primary:
// Good - connects to replica set
mongodb://primary:27017,secondary1:27017,secondary2:27017/?replicaSet=myReplicaSetConnect to any replica set member using the MongoDB shell and check which node is the primary:
mongosh
rs.status()Look for the member with "stateStr" : "PRIMARY" in the output. Verify all members show a valid state (PRIMARY, SECONDARY, ARBITER). Any members in STARTUP, RECOVERING, or UNKNOWN states indicate potential issues.
If your connection string is hardcoded to a specific node, update it to use the replica set name instead:
// Node.js example
const uri = "mongodb://primary:27017,secondary1:27017,secondary2:27017/?replicaSet=mySet";
const client = new MongoClient(uri, { retryWrites: true });# Python example
from pymongo import MongoClient
uri = "mongodb://primary:27017,secondary1:27017,secondary2:27017/?replicaSet=mySet"
client = MongoClient(uri)Ensure your application is not explicitly setting read preference to "secondary" or "secondaryPreferred" for write operations:
// Node.js - use primary read preference for writes
const db = client.db("mydb", { readPreference: "primary" });
const result = await db.collection("users").insertOne({ name: "John" });# Python - correct read preference
from pymongo import ReadPreference
client = MongoClient(uri, readPreference=ReadPreference.PRIMARY)If you just experienced a primary failure, wait 10-30 seconds for MongoDB to automatically elect a new primary. During this election window, write operations will fail. Most MongoDB drivers automatically retry failed operations once the new primary is elected.
You can monitor the election progress:
rs.status()Wait until one member shows "stateStr" : "PRIMARY".
Verify all replica set members can communicate with each other. Test connectivity:
# From each node, test connectivity to other nodes
telnet host2 27017
telnet host3 27017If any connections fail, check firewall rules, security groups, and network configuration. All replica set members must have bidirectional connectivity on the MongoDB port (default 27017).
For a replica set to elect a primary, a majority of voting members must be online:
- 3-member set: need 2 members available
- 5-member set: need 3 members available
- 2-member set + arbiter: need primary + arbiter
If you have multiple downed members, bring them back online or remove them from the replica set configuration:
rs.remove("hostname:27017")During initial sync (STARTUP2 phase), a newly added replica set member cannot accept writes and will return this error. This is normal behavior—wait for the member to complete initial sync before treating it as a full replica set member.
For MongoDB Atlas users, primary failures typically resolve automatically within seconds as Atlas manages failover. The application should retry operations with exponential backoff.
If using connection pooling, ensure the pool is configured to refresh its view of the replica set topology. Most modern drivers do this automatically, but some frameworks require explicit configuration.
When using transactions across multiple documents, ensure the transaction is executed against the primary. Secondary nodes cannot participate in transactions.
DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work
How to fix "DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work" in MongoDB
MongoServerError: bad auth : authentication failed
How to fix "MongoServerError: bad auth : authentication failed" in MongoDB
CannotCreateIndex: Cannot create index
CannotCreateIndex: Cannot create index
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB