How to fix NotWritablePrimary: not primary in MongoDB
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.
Quick fix
Fixes NotWritablePrimary: not primary
mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=rs0- Verify you are connecting to the correct replica set
- Check the current replica set status
- Update your application connection string if needed
- Verify read preference is set to primary for writes
mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=rs0NotWritablePrimary: not primary
What this error means
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.
Typical symptoms
- Write operations fail with error code 10107
- Insert, update, or delete operations are rejected
- Application throws "NotWritablePrimary: not primary" exceptions
- Database operations work intermittently during replica set elections
- Timeouts when attempting to write to the database
Common causes
- Connection string explicitly points to a secondary node instead of the primary
- Primary node has failed and client has not reconnected to the new elected primary
- Primary node is in the process of stepping down during failover
- Read preference is set to "secondary" while attempting a write operation
- Network connectivity issues preventing client from reaching the primary node
- Replica set member is still in STARTUP2 (initial sync) phase and cannot accept writes
- Client driver is cached with stale replica set topology information
How to fix "NotWritablePrimary: not primary"
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")Advanced notes
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.
Frequently asked questions
- What does "NotWritablePrimary: not primary" mean?
- 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.
- How do I fix "NotWritablePrimary: not primary"?
- 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.
- What causes "NotWritablePrimary: not primary"?
- Connection string explicitly points to a secondary node instead of the primary Primary node has failed and client has not reconnected to the new elected primary Primary node is in the process of stepping down during failover
- Is the "NotWritablePrimary: not primary" error serious?
- Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.
Official resources & further reading
- 📚MongoDB Official Documentation
- 📖MongoDB Atlas - Fix Lost Primary(Official Docs)
- 📖MongoDB Manual - Force Primary Election(Official Docs)
- 📖MongoDB Manual - Troubleshoot Replica Sets(Official Docs)
- 💬MongoDB Community - NotWritablePrimary Error(Stack Overflow)