What is MongoDB?
MongoDB is a document database: it stores data as BSON documents (JSON-like objects with nested fields and arrays) grouped in collections, instead of rows in tables. Documents in one collection can have different fields. It has secondary indexes, an aggregation pipeline, multi-document ACID transactions, replica sets for availability and sharding to scale out. The Community Server is free under the SSPL; MongoDB Atlas is the managed cloud version.
What is the difference between MongoDB and a SQL database?
SQL database MongoDB Unit of data Row in a table Document in a collection Schema Fixed, declared first Flexible, validation optional Relations Foreign keys and JOINs Embedding, or references with $lookupScaling writes Mostly a bigger server Sharding across servers Query language SQL Query documents and aggregation pipelines Both have indexes and ACID transactions. MongoDB fits data that is hierarchical or varies per record; SQL fits highly relational data queried in many unplanned ways. Compare with the SQL interview questions.
What are documents and collections in MongoDB?
A document is one record: field and value pairs, like a JSON object, that can nest objects and arrays. A collection is a group of documents, like a table without a fixed schema, and a database holds collections. A collection is created the first time you insert into it.
Node.jsconst { MongoClient } = require('mongodb'); const client = new MongoClient('mongodb://localhost:27017'); async function main() { const users = client.db('shop').collection('users'); await users.insertOne({ name: 'Asha', skills: ['js'], address: { city: 'Pune' } }); const asha = await users.findOne({ name: 'Asha' }, { projection: { _id: 0 } }); console.log(asha); } main().finally(() => client.close());What is BSON, and why does MongoDB use it instead of JSON?
BSON (Binary JSON) is the binary format MongoDB uses to store documents and send them over the network. Each element is tagged with its type and strings and embedded documents are length-prefixed, so the server can skip over fields quickly, and it has types JSON lacks:
ObjectId,Date, 32 and 64-bit integers,Decimal128and binary data. Drivers convert BSON to your language's objects, so you rarely handle it directly.What is the
_idfield, and what is an ObjectId?Every document has an
_idthat is unique in its collection, backed by an index MongoDB creates automatically. If you insert a document without one, the driver adds anObjectId: 12 bytes made of a 4-byte timestamp in seconds, a 5-byte random value per process and a 3-byte counter. ObjectIds are therefore roughly ordered by creation time._idcan be any type except an array, and it cannot be changed after insert.Node.jsconst { ObjectId } = require('mongodb'); const id = new ObjectId(); console.log(id.toHexString().length); console.log(ObjectId.isValid('64b7f0c2a1b2c3d4e5f60718'), ObjectId.isValid('abc')); console.log(id.getTimestamp() instanceof Date);Does
insertOnechange the object you pass to it?Node.jsconst { MongoClient } = require('mongodb'); const client = new MongoClient('mongodb://localhost:27017'); async function main() { const users = client.db('shop').collection('users'); const user = { name: 'Asha' }; const result = await users.insertOne(user); console.log('_id' in user, result.insertedId.equals(user._id)); } main().finally(() => client.close());It prints
true true. The Node.js driver adds the generated_idto the object you pass and returns the same id asinsertedId. So inserting the same object twice fails with a duplicate key error, because the second insert reuses that_id. Insert a copy ({ ...user }) when you reuse an object in a loop.What happens when you insert two documents with the same
_id?Node.jsconst { MongoClient } = require('mongodb'); const client = new MongoClient('mongodb://localhost:27017'); async function main() { const users = client.db('shop').collection('users'); await users.insertOne({ _id: 1, name: 'Asha' }); try { await users.insertOne({ _id: 1, name: 'Ravi' }); } catch (err) { console.log('error', err.code); } console.log(await users.countDocuments()); } main().finally(() => client.close());It prints
error 11000and then1._idhas a unique index, so the second insert is refused with error code 11000 (duplicate key) and the first document stays as it was. An insert never overwrites; to insert or replace, usereplaceOnewithupsert: true.Is MongoDB schemaless?
No, it has a flexible schema. Documents in one collection can have different fields, and adding a field needs no migration. The application still expects a shape, so production collections usually enforce one with JSON Schema validation (
$jsonSchema) or through an ODM such as Mongoose. Flexible means the database does not force one shape; it does not mean you skip design.What is the maximum size of a MongoDB document?
16 MB per document, with at most 100 levels of nesting. The limit keeps one document from using too much RAM or bandwidth. Hitting it usually means an array that grows without bound, such as every comment or log line: move those items into their own collection. For files larger than 16 MB, use GridFS, which splits a file into chunks (255 KB by default) stored in two collections.
Which data types does MongoDB support?
The BSON types: string, double, 32 and 64-bit integers,
Decimal128, boolean,Date,ObjectId, null, arrays, embedded documents, binary data, regular expressions andTimestamp. Two choices come up often: store dates asDate, not strings, so range queries and date operators work, and store money asDecimal128or integer cents, never as a double. Numeric types compare by value, so{ age: 30 }matches 30 stored as an int, a long or a double.What is mongosh, and how do shell commands map to the Node.js driver?
mongosh is MongoDB's shell: a JavaScript REPL connected to a server, and the syntax most interview questions use (
db.collection.method()). The Node.js driver has the same method names, but every call returns a promise andfindreturns a cursor you turn into an array.// mongosh db.orders.find({ status: 'paid' }).sort({ total: -1 }).limit(5) // Node.js driver const top = await client.db('shop').collection('orders') .find({ status: 'paid' }).sort({ total: -1 }).limit(5).toArray();More in MongoDB with Node.js.
When should you not use MongoDB?
When the data is highly relational and queried across many entities in ways you cannot predict, such as ad hoc reporting or accounting with many joins:
$lookupexists, but it is not the main access path. Also when you need foreign keys and other cross-record constraints enforced by the database, which MongoDB does not have. It fits catalogs, content, user profiles, events and data whose shape varies.Where does MongoDB sit in the CAP theorem?
With default settings it behaves as CP: all writes go to one primary, and during a network partition the side without a majority of voting members cannot elect a primary, so it stops taking writes instead of letting the data diverge. You can trade consistency for availability per operation: reads from secondaries can be stale, and a weak write concern (
w: 1) can lose acknowledged writes on failover.
MongoDB Basics Interview Questions
What a first MongoDB round checks: documents and collections, BSON, the _id field and how MongoDB differs from a SQL database.