Menu
CoddyTech

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.

13 questions
  1. 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.

  2. What is the difference between MongoDB and a SQL database?

    SQL databaseMongoDB
    Unit of dataRow in a tableDocument in a collection
    SchemaFixed, declared firstFlexible, validation optional
    RelationsForeign keys and JOINsEmbedding, or references with $lookup
    Scaling writesMostly a bigger serverSharding across servers
    Query languageSQLQuery 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.

  3. 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.js
    const { 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());
  4. 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, Decimal128 and binary data. Drivers convert BSON to your language's objects, so you rarely handle it directly.

  5. What is the _id field, and what is an ObjectId?

    Every document has an _id that is unique in its collection, backed by an index MongoDB creates automatically. If you insert a document without one, the driver adds an ObjectId: 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. _id can be any type except an array, and it cannot be changed after insert.

    Node.js
    const { 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);
  6. Does insertOne change the object you pass to it?

    Node.js
    const { 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 _id to the object you pass and returns the same id as insertedId. 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.

  7. What happens when you insert two documents with the same _id?

    Node.js
    const { 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 11000 and then 1. _id has 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, use replaceOne with upsert: true.

  8. 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.

  9. 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.

  10. 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 and Timestamp. Two choices come up often: store dates as Date, not strings, so range queries and date operators work, and store money as Decimal128 or 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.

  11. 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 and find returns 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.

  12. 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: $lookup exists, 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.

  13. 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.

Coddy programming languages illustration

Learn to code with Coddy

Get started