Does MongoDB support ACID transactions?
Yes. A write to a single document has always been atomic, including its embedded documents and arrays. Multi-document ACID transactions arrived in MongoDB 4.0 for replica sets and 4.2 for sharded clusters. They cost more than single-document writes, so a good schema keeps data that changes together in one document and saves transactions for writes that span several, such as moving money between two accounts.
How do you run a transaction with the Node.js driver?
Start a session and pass it to every operation.
withTransactioncommits when the callback finishes, aborts if it throws, and retries the whole callback on transient errors such as write conflicts. Transactions need a replica set or a sharded cluster, not a standalone server.const session = client.startSession(); try { await session.withTransaction(async () => { const accounts = client.db('bank').collection('accounts'); const debit = await accounts.updateOne( { _id: 'asha', balance: { $gte: 100 } }, { $inc: { balance: -100 } }, { session } ); if (debit.modifiedCount !== 1) throw new Error('insufficient funds'); await accounts.updateOne({ _id: 'ravi' }, { $inc: { balance: 100 } }, { session }); }); } finally { await session.endSession(); }What are the limits and costs of MongoDB transactions?
By default a transaction must finish within 60 seconds (
transactionLifetimeLimitSeconds) or the server aborts it. Two transactions writing the same document cause a write conflict, and one has to retry. Uncommitted changes are held in the WiredTiger cache, so MongoDB advises modifying no more than about 1,000 documents per transaction and splitting larger jobs. UsewriteConcern: 'majority'when the result must survive a failover.What is a replica set?
A group of
mongodservers holding the same data: one primary that takes all writes and secondaries that copy its operations. If the primary fails, the members elect a new one automatically, so a replica set gives redundancy and high availability. A typical production set has three data-bearing members; a set can have up to 50 members, at most 7 of them voting.How does failover work in a replica set?
Members send each other heartbeats every 2 seconds. If the primary does not respond within
electionTimeoutMillis(10 seconds by default), a secondary calls an election and becomes primary if a majority of voting members vote for it; members with stale data cannot win. A new primary is usually in place within about 12 seconds. Meanwhile writes fail, and drivers retry a failed write once (retryable writes).What is an arbiter, and why is a majority needed?
An arbiter votes in elections but stores no data, a cheap way to get an odd number of voters. A majority is required so that two sides of a network split can never both elect a primary: only the side with more than half the votes can. With two data members and an arbiter, losing one data member leaves nobody to acknowledge
w: 'majority'writes, so three data-bearing members are preferred.What is the oplog?
The operations log: a capped collection (
local.oplog.rs) on every member, where the primary records each write as an idempotent operation (an$incis recorded as the resulting value). Secondaries copy it and replay it. Its size sets the replication window: a secondary that is down longer than the oplog covers must resync from scratch. Change streams read from it too.How do you choose a shard key?
Look for high cardinality (many distinct values), low frequency (no value in a large share of documents), and a value that does not only increase, because a key such as a timestamp or a default ObjectId sends every insert to the same shard. The key should also appear in most queries, so the router can target one shard. A compound key such as
{ customerId: 1, orderDate: 1 }often meets all three.What is the difference between hashed and ranged sharding?
Ranged sharding splits data into contiguous ranges of the shard key, so range queries touch few shards, but an increasing key makes one shard hot. Hashed sharding splits by a hash of the key, which spreads increasing keys such as ObjectIds evenly, but a range query on the key must go to every shard. Use hashed for write-heavy keys you look up by equality, ranged when queries ask for ranges.
Can you change a collection's shard key?
Yes, since MongoDB 5.0:
reshardCollectionrewrites the data under a new key while the cluster stays online, which is slow and heavy on a large collection. MongoDB 4.4 addedrefineCollectionShardKey, which appends fields to the existing key, a cheaper fix for low cardinality. Since 4.2 you can also update a document's shard key value. Before that, the only way out was to dump and reload the data.What is a scatter-gather query in a sharded cluster?
A query without the shard key:
mongoscannot tell which shards hold the data, so it sends the query to all of them and merges the results. It works, but the slowest shard sets the latency and every shard does the work. A query that includes the shard key, or a prefix of it, is targeted at one shard or a few.explainlists the shards a query touched.
MongoDB Transactions, Replication and Sharding Questions
How MongoDB keeps data consistent and available: ACID transactions, replica sets and failover, and scaling out with sharding and shard keys.