MongoDB Errors

Browse server error codes and driver error classes with explanations and diagnostic guidance.

JavaMongoBulkWriteException
An exception that indicates one or more errors occurred during a bulk write operation
writeserver
JavaMongoClientException
An exception indicating a problem with the MongoClient configuration or state
general
JavaMongoCommandException
An exception indicating that a command sent to a MongoDB server returned a failure
server
JavaMongoConfigurationException
An exception indicating invalid configuration of the MongoDB client (e.g. malformed connection string)
configuration
JavaMongoException
Base exception for all MongoDB Java driver errors
driver
JavaMongoInternalException
An exception indicating an internal driver error that should not normally occur
general
JavaMongoInterruptedException
An exception indicating that the thread executing a MongoDB operation was interrupted
general
JavaMongoNodeIsRecoveringException
An exception indicating the server is in a recovering state and cannot accept the operation
server
JavaMongoNotPrimaryException
An exception indicating the server is not the primary and the operation requires a primary
server
JavaMongoQueryException
An exception indicating that a query operation on a MongoDB server has failed
server
JavaMongoSecurityException
An exception indicating that authentication with the MongoDB server failed
authentication
JavaMongoServerException
An exception that represents an error response from the MongoDB server
general
JavaMongoSocketException
A failure in the underlying socket communication with a MongoDB server
connectivitynetworking
JavaMongoSocketOpenException
An exception indicating that a socket could not be opened to a MongoDB server
connectivity
JavaMongoSocketReadException
An exception indicating a failure to read from a MongoDB server socket
connectivity
JavaMongoSocketReadTimeoutException
An exception indicating that a socket read timed out (no data received within the configured timeout)
timeoutconnectivity
JavaMongoSocketWriteException
An exception indicating a failure to write to a MongoDB server socket
connectivitywrite
JavaMongoTimeoutException
The driver timed out waiting for a suitable server or for the operation to complete
connectivitytimeout
JavaMongoWriteConcernException
An exception that indicates a write concern was not fulfilled within the specified time limit
writeserver
JavaMongoWriteException
An exception indicating an error on a write operation (e.g. duplicate key, write concern failure)
writeserver
Node.jsMongoAPIError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string, options?: { cause?: Error }) { super(message, options); } override get name(): string { return 'MongoDriverError'; } } /** An error generated when the driver API is used incorrectly Should **never** be directly instantiated
driver
Node.jsMongoAWSError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoKerberosError'; } } /** A error generated when the user attempts to authenticate via AWS, but fails
driver
Node.jsMongoAzureError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoOIDCError'; } } /** A error generated when the user attempts to authenticate via Azure, but fails.
general
Node.jsMongoBatchReExecutionError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string, options?: { cause?: Error }) { super(message, options); } override get name(): string { return 'MongoStalePrimaryError'; } } /** An error generated when a batch command is re-executed after one of the commands in the batch has failed
driver
Node.jsMongoChangeStreamError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoClientBulkWriteExecutionError'; } } /** An error generated when a ChangeStream operation fails to execute.
change_streamsdriver
Node.jsMongoClientBulkWriteCursorError
Write concern errors that occurred while executing the bulk write. This list may have multiple items if more than one server command was required to execute the bulk write. / writeConcernErrors: Document[]; /** Errors that occurred during the execution of individual write operations. This map will contain at most one entry if the bulk write was ordered. / writeErrors: Map<number, ClientBulkWriteError>; /** The results of any successful operations that were performed before the error was encountered. / partialResult?: ClientBulkWriteResult; /** Initialize the client bulk write error. / constructor(message: ErrorDescription) { super(message); this.writeConcernErrors = []; this.writeErrors = new Map(); } override get name(): string { return 'MongoClientBulkWriteError'; } } /** An error indicating that an error occurred when processing bulk write results.
writecursordriver
Node.jsMongoClientBulkWriteError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoGCPError'; } } /** An error indicating that an error occurred when executing the bulk write.
writeserver
Node.jsMongoClientBulkWriteExecutionError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoClientBulkWriteCursorError'; } } /** An error indicating that an error occurred on the client when executing a client bulk write.
writedriver
Node.jsMongoClientClosedError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message = 'Topology is closed') { super(message); } override get name(): string { return 'MongoTopologyClosedError'; } } /** An error generated when the MongoClient is closed and async operations are interrupted.
driver
Node.jsMongoCompatibilityError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string, options?: { cause?: Error }) { super(message, options); } override get name(): string { return 'MongoInvalidArgumentError'; } } /** An error generated when a feature that is not enabled or allowed for the current server configuration is used
driver
Node.jsMongoCursorExhaustedError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message = 'Server is closed') { super(message); } override get name(): string { return 'MongoServerClosedError'; } } /** An error thrown when an attempt is made to read from a cursor that has been exhausted
cursordriver
Node.jsMongoCursorInUseError
An error thrown when the user attempts to add options to a cursor that has already been initialized
cursordriver
Node.jsMongoDecompressionError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message = 'This batch has already been executed, create new batch to execute') { super(message); } override get name(): string { return 'MongoBatchReExecutionError'; } } /** An error generated when the driver fails to decompress data received from the server.
driver
Node.jsMongoDriverError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: ErrorDescription) { super(message.message || message.errmsg || message.$err || 'n/a'); if (message.errorLabels) { for (const label of message.errorLabels) this.addErrorLabel(label); } this.errorResponse = message; for (const name in message) { if ( name !== 'errorLabels' && name !== 'errmsg' && name !== 'message' && name !== 'errorResponse' ) { this[name] = message[name]; } } } override get name(): string { return 'MongoServerError'; } } /** An error generated by the driver
general
Node.jsMongoError
The legacy error message from the server that indicates the node is not a writable primary https://github.com/mongodb/specifications/blob/921232976f9913cf17415b5ef937ee772e45e6ae/source/server-discovery-and-monitoring/server-discovery-and-monitoring.md#not-writable-primary-and-node-is-recovering / export const LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp('not master', 'i'); /** The legacy error message from the server that indicates the node is not a primary or secondary https://github.com/mongodb/specifications/blob/921232976f9913cf17415b5ef937ee772e45e6ae/source/server-discovery-and-monitoring/server-discovery-and-monitoring.md#not-writable-primary-and-node-is-recovering / export const LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp( 'not master or secondary', 'i' ); /** The error message from the server that indicates the node is recovering https://github.com/mongodb/specifications/blob/921232976f9913cf17415b5ef937ee772e45e6ae/source/server-discovery-and-monitoring/server-discovery-and-monitoring.md#not-writable-primary-and-node-is-recovering / export const NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp('node is recovering', 'i'); /** @internal MongoDB Error Codes */ export const MONGODB_ERROR_CODES = Object.freeze({ HostUnreachable: 6, HostNotFound: 7, AuthenticationFailed: 18, NetworkTimeout: 89, ShutdownInProgress: 91, PrimarySteppedDown: 189, ExceededTimeLimit: 262, SocketException: 9001, NotWritablePrimary: 10107, InterruptedAtShutdown: 11600, InterruptedDueToReplStateChange: 11602, NotPrimaryNoSecondaryOk: 13435, NotPrimaryOrSecondary: 13436, StaleShardVersion: 63, StaleEpoch: 150, StaleConfig: 13388, RetryChangeStream: 234, FailedToSatisfyReadPreference: 133, CursorNotFound: 43, LegacyNotPrimary: 10058, // WriteConcernTimeout is WriteConcernFailed on pre-8.1 servers WriteConcernTimeout: 64, NamespaceNotFound: 26, IllegalOperation: 20, MaxTimeMSExpired: 50, UnknownReplWriteConcern: 79, UnsatisfiableWriteConcern: 100, Reauthenticate: 391, ReadConcernMajorityNotAvailableYet: 134 } as const); /** Matches on `code` alone, so any error type works. `Number()` because `code` is a BSON Int32 when `promoteValues` is false. / export function isNamespaceNotFoundError(error: unknown): boolean { return ( Number((error as { code?: unknown } | null)?.code) === MONGODB_ERROR_CODES.NamespaceNotFound ); } // From spec https://github.com/mongodb/specifications/blob/921232976f9913cf17415b5ef937ee772e45e6ae/source/change-streams/change-streams.md#resumable-error export const GET_MORE_RESUMABLE_CODES = new Set<number>([ MONGODB_ERROR_CODES.HostUnreachable, MONGODB_ERROR_CODES.HostNotFound, MONGODB_ERROR_CODES.NetworkTimeout, MONGODB_ERROR_CODES.ShutdownInProgress, MONGODB_ERROR_CODES.PrimarySteppedDown, MONGODB_ERROR_CODES.ExceededTimeLimit, MONGODB_ERROR_CODES.SocketException, MONGODB_ERROR_CODES.NotWritablePrimary, MONGODB_ERROR_CODES.InterruptedAtShutdown, MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, MONGODB_ERROR_CODES.NotPrimaryOrSecondary, MONGODB_ERROR_CODES.StaleShardVersion, MONGODB_ERROR_CODES.StaleEpoch, MONGODB_ERROR_CODES.StaleConfig, MONGODB_ERROR_CODES.RetryChangeStream, MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, MONGODB_ERROR_CODES.CursorNotFound ]); /** @public */ export const MongoErrorLabel = Object.freeze({ RetryableWriteError: 'RetryableWriteError', TransientTransactionError: 'TransientTransactionError', UnknownTransactionCommitResult: 'UnknownTransactionCommitResult', ResumableChangeStreamError: 'ResumableChangeStreamError', HandshakeError: 'HandshakeError', ResetPool: 'ResetPool', PoolRequestedRetry: 'PoolRequestedRetry', InterruptInUseConnections: 'InterruptInUseConnections', NoWritesPerformed: 'NoWritesPerformed', RetryableError: 'RetryableError', SystemOverloadedError: 'SystemOverloadedError' } as const); /** @public */ export type MongoErrorLabel = (typeof MongoErrorLabel)[keyof typeof MongoErrorLabel]; /** @public */ export interface ErrorDescription extends Document { message?: string; errmsg?: string; $err?: string; errorLabels?: string[]; errInfo?: Document; } function isAggregateError(e: unknown): e is Error & { errors: Error[] } { return e != null && typeof e === 'object' && 'errors' in e && Array.isArray(e.errors); } /** mongodb-client-encryption has a dependency on this error, it uses the constructor with a string argument
general
Node.jsMongoExpiredSessionError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoTransactionError'; } } /** An error generated when the user attempts to operate on a session that has expired or has been closed.
driver
Node.jsMongoGCPError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoAzureError'; } } /** A error generated when the user attempts to authenticate via GCP, but fails.
general
Node.jsMongoGridFSChunkError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoGridFSStreamError'; } } /** An error generated when a malformed or invalid chunk is encountered when reading from a GridFSStream.
gridfsdriver
Node.jsMongoGridFSStreamError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message = 'Tailable cursor does not support this operation') { super(message); } override get name(): string { return 'MongoTailableCursorError'; } } /** An error generated when a GridFSStream operation fails to execute.
gridfsdriver
Node.jsMongoInvalidArgumentError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoParseError'; } } /** An error generated when the user supplies malformed or unexpected arguments or when a required argument or field is not provided.
configurationdriver
Node.jsMongoKerberosError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message = 'Cannot use a session that has ended') { super(message); } override get name(): string { return 'MongoExpiredSessionError'; } } /** A error generated when the user attempts to authenticate via Kerberos, but fails to connect to the Kerberos client.
securitydriver
Node.jsMongoMissingCredentialsError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoCompatibilityError'; } } /** An error generated when the user fails to provide authentication credentials before attempting to connect to a mongo server instance.
authenticationdriver
Node.jsMongoMissingDependencyError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoMissingCredentialsError'; } } /** An error generated when a required module or dependency is not present in the local environment
driver
Node.jsMongoNetworkError
A network-level error occurred during communication with the MongoDB server
connectivitynetworking
Node.jsMongoNetworkTimeoutError
A network operation timed out (socket timeout or connect timeout exceeded)
connectivitynetworkingtimeout
Node.jsMongoNotConnectedError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoDecompressionError'; } } /** An error thrown when the user attempts to operate on a database or collection through a MongoClient that has not yet successfully called the "connect" method
driver
Node.jsMongoOIDCError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string, options?: { cause?: Error }) { super(message, options); } override get name(): string { return 'MongoAWSError'; } } /** A error generated when the user attempts to authenticate via OIDC callbacks, but fails.
securitydriver
Node.jsMongoOperationTimeoutError
The client-side operation timeout (timeoutMS) was exceeded before the operation completed
timeoutperformance
Node.jsMongoParseError
The connection string or URI options could not be parsed
configurationconnectivity
Node.jsMongoRuntimeError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string, options?: { cause?: Error }) { super(message, options); } override get name(): string { return 'MongoAPIError'; } } /** An error generated when the driver encounters unexpected input or reaches an unexpected/invalid internal state. Should **never** be directly instantiated.
timeoutdriver
Node.jsMongoServerClosedError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message = 'Cursor is already initialized') { super(message); } override get name(): string { return 'MongoCursorInUseError'; } } /** An error generated when an attempt is made to operate on a closed/closing server.
driver
Node.jsMongoServerError
An error response received from the MongoDB server (as opposed to a driver-side error)
server
Node.jsMongoServerSelectionError
The driver could not select a suitable server for the operation within serverSelectionTimeoutMS
connectivitytopologytimeout
Node.jsMongoStalePrimaryError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string, options?: { cause?: Error }) { super(message, options); } override get name(): string { return 'MongoRuntimeError'; } } /** An error generated when a primary server is marked stale, never directly thrown
driver
Node.jsMongoSystemError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string, options: { cause: Error; dependencyName: string }) { super(message, options); this.dependencyName = options.dependencyName; } override get name(): string { return 'MongoMissingDependencyError'; } } /** An error signifying a general system issue
general
Node.jsMongoTailableCursorError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoChangeStreamError'; } } /** An error thrown when the user calls a function or method not supported on a tailable cursor
cursordriver
Node.jsMongoTopologyClosedError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message?: string) { super(message || 'Cursor is exhausted'); } override get name(): string { return 'MongoCursorExhaustedError'; } } /** An error generated when an attempt is made to operate on a dropped, or otherwise unavailable, database.
topologydriver
Node.jsMongoTransactionError
An error related to multi-document transaction usage
transaction
Node.jsMongoUnexpectedServerResponseError
not subject to semantic versioning compatibility guarantees and may change at any time. */ constructor(message: string) { super(message); } override get name(): string { return 'MongoGridFSChunkError'; } } /** An error generated when a **parsable** unexpected response comes from the server. This is generally an error where the driver in a state expecting a certain behavior to occur in the next message from MongoDB but it receives something else. This error **does not** represent an issue with wire message formatting. #### Example When an operation fails, it is the driver's job to retry it. It must perform serverSelection again to make sure that it attempts the operation against a server in a good state. If server selection returns a server that does not support retryable operations, this error is used. This scenario is unlikely as retryable support would also have been determined on the first attempt but it is possible the state change could report a selectable server that does not support retries.
driver
Node.jsMongoWriteConcernError
The write operation succeeded but the write concern could not be satisfied
writereplicationconsistency
PyMongoAutoReconnect
Raised when a connection to the database is lost and an attempt to auto-reconnect will be made. Application code should handle this and retry the operation.
general
PyMongoBulkWriteError
Raised when one or more errors occur during a bulk write operation
write
PyMongoConfigurationError
Raised when a configuration error is detected (e.g. malformed URI, invalid option)
configuration
PyMongoConnectionFailure
A connection to the MongoDB database cannot be made or was lost
connectivitynetworking
PyMongoCursorNotFound
Raised when a cursor used in a getMore operation is not found on the server (cursor may have timed out)
cursor
PyMongoDocumentTooLarge
Raised when a document exceeds the maximum BSON document size (16MB)
general
PyMongoDuplicateKeyError
Raised when a write attempts to create a duplicate value in a unique index (server error code 11000)
general
PyMongoEncryptionError
Raised when client-side field level encryption or auto-encryption fails
security
PyMongoExecutionTimeout
Raised when an operation exceeds the server-side maxTimeMS limit
timeout
PyMongoInvalidDocument
Raised when a document cannot be encoded to BSON (e.g. unsupported type, circular reference)
configuration
PyMongoInvalidOperation
Raised when an invalid operation is attempted (e.g. using a closed client, modifying a cursor after execution)
configuration
PyMongoInvalidURI
Raised when the MongoDB connection URI is malformed or contains invalid options
configuration
PyMongoNetworkTimeout
An operation on an open connection exceeded socketTimeoutMS. The connection is closed.
timeoutconnectivity
PyMongoOperationFailure
Raised when a database operation fails. Includes the server error code and details.
general
PyMongoPyMongoError
Base class for all PyMongo exceptions
general
PyMongoServerSelectionTimeoutError
No MongoDB server matching the selection criteria was found within serverSelectionTimeoutMS
connectivitytopologytimeout
PyMongoWriteConcernError
Raised when a write operation succeeds but the write concern was not satisfied
write
PyMongoWriteError
Base class for errors from individual write operations (inserts, updates, deletes)
write