db.createCollection() — MongoDB Technical Interview Questions & Answers
Explicitly creates a new collection, with options.
db.createCollection()
- Simple meaning: db.createCollection("students") makes a collection before the first insert. Usually you skip this — insertOne creates it.
- How to use: when you need options: capped size, validator $jsonSchema, collation.
- Try this: db.createCollection("logs", { capped: true, size: 1048576 }).
- Common mistake: thinking you must createCollection for every table like SQL CREATE TABLE.
- Interview tip: Implicit create on insert. Explicit when you need options.
Technical Interview Tip: Explicit create = options. Else just insert.
Code Examples for db.createCollection()
db.createCollection() — working example
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email"],
properties: {
email: { bsonType: "string" },
age: { bsonType: "int", minimum: 0 }
}
}
}
})
// Or implicitly:
db.orders.insertOne({ orderId: "O-1", amount: 499 })db.createCollection() — collections are often created on first insert; createCollection sets options like validators.
How to Explain db.createCollection() to an Interviewer
Must you createCollection first?
No — first insert creates it Yes if you need capped/validator