5.1 Answers- Backend & Database Interview Questions
5.1 Answers- Backend & Database Interview Questions
Example:
○
javascript
2. How does Node.js differ from traditional web
Copy code
servers like Apache?
○ Node.js uses an event-driven, non-blocking const express = require('express');
I/O model which makes it lightweight and const app = express();
efficient. Unlike Apache, which creates a new
thread for each request, Node.js handles ○
multiple requests on a single thread using 8. What is the difference between require and
asynchronous callbacks. import in Node.js?
3. Explain the characteristics of Node.js that make it ○ require is used in CommonJS module
suitable for building scalable applications.
system, while import is used in ES6
○ Non-blocking I/O: Handles many connections
modules. Node.js natively supports
concurrently.
CommonJS, but ES6 modules can be used
○ Event-driven architecture: Efficiently handles
asynchronous operations. with the .mjs extension or with specific
○ Single-threaded: Uses fewer resources and is configurations.
easier to manage.
4. What is npm? How do you use it in Node.js Example:
projects? javascript
○ npm (Node Package Manager) is a package Copy code
manager for JavaScript, included with // CommonJS
Node.js. It helps install, update, and manage const express = require('express');
packages.
// ES6
Example:
import express from 'express';
sh
Copy code
○
// Initialize a new Node.js project
9. How do you create and publish your own npm
npm init -y package?
○ Create a package.json file, write your
// Install a package (e.g., Express) code, and use npm publish to publish the
npm install express package.
○ Example:
5. What are the advantages of using Node.js? sh
○ High performance due to V8 engine. Copy code
○ Efficient handling of concurrent connections. // Initialize project
○ Large ecosystem with npm. npm init
Copy code
// Create main file (index.js) const fs = require('fs').promises;
echo "module.exports = () => console.log('Hello,
world!');" > index.js fs.readFile('file.txt', 'utf8')
.then(data => console.log('File data:', data))
// Publish the package .catch(err => console.error('Error reading
npm publish file:', err));
○ ○
10. What are the built-in modules in Node.js? 15. What are async/await in Node.js? How do they
○ Some built-in modules include http, fs, work?
path, url, crypto, and events. ○ async/await is syntactic sugar built on top
of Promises, making asynchronous code look
and behave more like synchronous code.
Example:
javascript
Copy code Example:
const fs = require('fs'); javascript
Copy code
fs.readFile('file.txt', 'utf8', (err, data) => {
const fs = require('fs').promises;
if (err) throw err;
console.log(data);
async function readFile() {
});
try {
const data = await fs.readFile('file.txt',
○
'utf8');
console.log('File data:', data);
Asynchronous Programming
} catch (err) {
11. Explain the concept of non-blocking I/O in Node.js. console.error('Error reading file:', err);
○ Non-blocking I/O means that operations like }
reading from a file or database do not block }
the execution of other operations. Instead,
they are executed asynchronously, allowing readFile();
other code to run concurrently.
12. How does Node.js handle asynchronous
○
operations?
○ Node.js uses callbacks, Promises, and
async/await to handle asynchronous File System Operations
operations.
13. What are callbacks in Node.js? How do you handle 16. How do you perform file operations in Node.js?
errors with callbacks? ○ Using the fs module for synchronous and
○ Callbacks are functions passed as arguments asynchronous file operations.
to other functions to be executed after the
completion of an operation. Example:
javascript
Example: Copy code
javascript const fs = require('fs');
Copy code
const fs = require('fs'); // Asynchronous read
fs.readFile('file.txt', 'utf8', (err, data) => {
fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err;
if (err) { console.log(data);
console.error('Error reading file:', err); });
return;
} // Synchronous read
console.log('File data:', data); const data = fs.readFileSync('file.txt',
}); 'utf8');
console.log(data);
○
14. Explain Promises in Node.js.
○
○ Promises represent the eventual completion
17. Explain the difference between synchronous and
(or failure) of an asynchronous operation and
asynchronous file operations in Node.js.
its resulting value.
○ Synchronous operations block the event loop
until the operation completes, while
Example: asynchronous operations do not block the
javascript
event loop and use callbacks, Promises, or res.send('Hello, World!');
async/await for the result. });
18. How do you handle streams in Node.js?
○ Streams are used to handle reading and
app.listen(3000, () => {
writing of large data efficiently. They are
console.log('Server running on port 3000');
instances of EventEmitter.
});
Example:
javascript ○
Copy code 21. Explain middleware in the context of Express.js.
const fs = require('fs'); ○ Middleware functions are functions that have
access to the request object (req), the
const readStream =
response object (res), and the next
fs.createReadStream('largefile.txt', 'utf8');
middleware function in the application’s
const writeStream =
request-response cycle.
fs.createWriteStream('output.txt');
Example:
readStream.on('data', chunk => { javascript
writeStream.write(chunk); Copy code
}); app.use((req, res, next) => {
console.log('Request URL:', req.url);
readStream.on('end', () => { next();
writeStream.end(); });
});
app.get('/', (req, res) => {
○ res.send('Hello, World!');
});
Web Servers and APIs
○
19. How do you create a simple HTTP server in 22. How do you handle routing in Express.js?
Node.js? ○ By defining route handlers for different HTTP
○ Using the http module. methods and URL paths.
Example: Example:
javascript javascript
Copy code Copy code
const http = require('http'); app.get('/', (req, res) => {
res.send('GET request to the homepage');
const server = http.createServer((req, res) => { });
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain'); app.post('/', (req, res) => {
res.end('Hello, World!\n'); res.send('POST request to the homepage');
}); });
Example: Example:
javascript javascript
Copy code Copy code
const express = require('express'); const express = require('express');
const app = express(); const app = express();
const bodyParser = require('body-parser');
app.get('/', (req, res) => {
app.use(bodyParser.json()); const db = mongoose.connection;
db.on('error', console.error.bind(console,
let items = []; 'connection error:'));
db.once('open', function() {
app.post('/items', (req, res) => { console.log('Connected to MongoDB');
const item = req.body; });
items.push(item);
res.status(201).send(item); ○
});
Example with MySQL:
javascript
app.get('/items', (req, res) => {
Copy code
res.send(items);
const mysql = require('mysql');
});
Example:
// Start application with PM2
javascript
pm2 start app.js
Copy code
// Error handling in async/await
○
async function getData() {
try {
These questions and answers cover essential topics in Node.js,
const data = await someAsyncFunction(); Express.js, and database integration, providing practical
console.log(data); examples to illustrate key concepts. Practicing these will help you
} catch (error) { prepare for interviews comprehensively.
console.error('Error:', error);
} 4o
}
continue
○
27. What tools and techniques do you use for ChatGPT
debugging Node.js applications?
○ Tools: node inspect, Chrome DevTools, Advanced Topics
Visual Studio Code debugger, and libraries
like debug. 31. What is the event loop in Node.js? How does it
work?
Example with debug library: ○ The event loop is a mechanism that allows
javascript Node.js to perform non-blocking I/O
Copy code operations by offloading operations to the
system kernel whenever possible. It
const debug = require('debug')('app');
processes asynchronous callbacks and
executes them in a single-threaded
debug('This is a debug message'); event-driven loop.
○ Example:
javascript
Security Copy code
console.log('Start');
28. What are some common security concerns in
Node.js applications? setTimeout(() => {
○ Injection attacks (SQL, NoSQL, Command), console.log('Timeout callback');
cross-site scripting (XSS), cross-site request
}, 0);
forgery (CSRF), and insecure dependencies.
29. How do you prevent common security
vulnerabilities in Node.js applications? console.log('End');
○ Use parameterized queries, sanitize user
input, use security headers, validate data, // Output:
keep dependencies up to date, and use tools // Start
like Helmet for setting HTTP headers. // End
// Timeout callback
Example:
javascript
○
Copy code
32. What are process.nextTick() and setImmediate()?
const helmet = require('helmet');
How do they differ?
app.use(helmet());
○ process.nextTick() schedules a
callback function to be invoked in the next
○ iteration of the event loop, before any I/O
operations.
Deployment and Performance ○ setImmediate() schedules a callback to
be executed after I/O events callbacks and
30. How do you deploy Node.js applications? What before timers.
considerations are important for deployment?
○ Deploy to platforms like Heroku, AWS, or Example:
DigitalOcean. Use process managers like javascript
PM2, and configure environments properly. Copy code
console.log('Start');
Example with PM2:
sh
process.nextTick(() => { if (isMainThread) {
console.log('Next Tick'); new Worker(__filename, { workerData: 'Hello,
}); Worker' });
} else {
setImmediate(() => { console.log(workerData); // 'Hello, Worker'
console.log('Immediate'); }
});
○
console.log('End');
Testing
// Output:
// Start 35. How do you write tests for Node.js applications?
// End What frameworks do you use?
○ Use testing frameworks like Mocha, Jest, and
// Next Tick
Chai to write and run tests.
// Immediate
Example with Mocha and Chai:
○ javascript
33. Explain the concept of clustering in Node.js. How Copy code
does it improve performance? const { expect } = require('chai');
○ Clustering allows Node.js to create multiple
const { add } = require('./math');
processes that share the same server port.
This is useful for taking advantage of
multi-core systems to handle more describe('Math Functions', () => {
concurrent connections. it('should add two numbers', () => {
const result = add(2, 3);
Example: expect(result).to.equal(5);
javascript });
Copy code
});
const cluster = require('cluster');
const http = require('http'); ○
const numCPUs = require('os').cpus().length; 36. What is the purpose of mocking in tests? How do
you use Sinon for mocking?
if (cluster.isMaster) { ○ Mocking simulates the behavior of complex
for (let i = 0; i < numCPUs; i++) { or external dependencies in tests, allowing
cluster.fork(); you to test units of code in isolation.
}
Example with Sinon:
javascript
cluster.on('exit', (worker, code, signal) => { Copy code
console.log(`Worker ${worker.process.pid} const sinon = require('sinon');
died`); const { expect } = require('chai');
}); const userService = require('./userService');
} else {
http.createServer((req, res) => { describe('User Service', () => {
res.writeHead(200); it('should call getUser once', () => {
res.end('Hello World\n'); const getUser = sinon.spy(userService,
}).listen(8000); 'getUser');
} userService.getUser(1);
expect(getUser.calledOnce).to.be.true;
○ getUser.restore();
34. What are worker threads in Node.js? How do they
});
differ from clustering?
○ Worker threads allow the execution of });
JavaScript code in parallel using multiple
threads. Unlike clustering, worker threads ○
can share memory and are suitable for 37. How do you handle asynchronous testing in
CPU-intensive tasks. Node.js?
○ Use done callback, Promises, or async/await
Example: to handle asynchronous code in tests.
javascript
Copy code Example with async/await:
const { Worker, isMainThread, parentPort, javascript
workerData } = require('worker_threads'); Copy code
const { expect } = require('chai');
const { fetchData } = require('./dataService');
console.log(process.env.DB_HOST); // Value from
describe('Data Service', () => { .env file
it('should fetch data', async () => {
const data = await fetchData(); ○
expect(data).to.equal('Expected Data'); 42. What are some best practices for structuring
Node.js applications?
});
○ Use a modular structure, separate business
});
logic from presentation, use middleware for
cross-cutting concerns, and follow the single
○ responsibility principle.
SQL Query: ■
sql
Copy code References:
SELECT * FROM users WHERE id = 1; javascript
Copy code
■ const post = { title: "Post Title", content:
"Post content..." };
NoSQL Query (MongoDB): db.posts.insert(post);
javascript const comment = { postId: post._id, user:
Copy code "Alice", text: "Great post!" };
db.users.find({ _id: 1 }); db.comments.insert(comment);
■ ■
54. How do you model many-to-many relationships in db.accounts.updateOne({ _id: 2 }, { $set: {
MongoDB? balance: 150 } }, { session });
○ Use an array of references to represent session.commitTransaction();
many-to-many relationships.
} catch (error) {
session.abortTransaction();
Example:
javascript } finally {
Copy code session.endSession();
const student = { name: "John Doe", courses: }
[course1_id, course2_id] };
const course = { title: "Math 101", students: ○
[student1_id, student2_id] };
db.students.insert(student); Replication and Sharding in MongoDB
db.courses.insert(course);
58. What is replication in MongoDB? How do you set
up a replica set?
○
○ Replication is the process of synchronizing
data across multiple servers to ensure high
Indexing and Performance in MongoDB availability and data redundancy.
try { Example:
db.users.updateOne({ _id: 1 }, { $set: { javascript
balance: 50 } }, { session }); Copy code
// Enable authentication in the configuration mongoose.connect('mongodb://localhost/test', {
file useNewUrlParser: true, useUnifiedTopology: true
security: });
authorization: "enabled"
const userSchema = new mongoose.Schema({
○ name: String,
61. How do you prevent NoSQL injection attacks in age: Number,
MongoDB?
email: String
○ Validate and sanitize user inputs, use
});
parameterized queries, and limit the types of
operations that users can perform.
const User = mongoose.model('User', userSchema);
Example:
javascript const newUser = new User({ name: 'John Doe',
Copy code age: 30, email: '[email protected]' });
const userId = sanitize(req.body.userId); newUser.save().then(() => console.log('User
db.users.findOne({ _id: userId }); saved!'));
○ ○
62. How do you integrate MongoDB with Node.js 64. How do you write tests for MongoDB interactions in
applications? Node.js applications?
○ Use the official MongoDB Node.js driver to ○ Use testing frameworks like Mocha and Chai,
connect and interact with MongoDB. and mock the database using tools like
mongodb-memory-server for in-memory
Example: MongoDB instances.
javascript
Copy code Example:
const { MongoClient } = require('mongodb'); javascript
const uri = "mongodb://localhost:27017"; Copy code
const client = new MongoClient(uri); const { MongoMemoryServer } =
require('mongodb-memory-server');
async function run() { const mongoose = require('mongoose');
try { const { expect } = require('chai');
await client.connect(); const User = require('./userModel'); // Assuming
const database = client.db('test'); a Mongoose model
const collection =
database.collection('users'); let mongoServer;
const user = await collection.findOne({ before(async () => {
name: "John Doe" }); mongoServer = new MongoMemoryServer();
console.log(user); const uri = await mongoServer.getUri();
} finally { await mongoose.connect(uri, { useNewUrlParser:
await client.close(); true, useUnifiedTopology: true });
} });
}
after(async () => {
run().catch(console.dir); await mongoose.disconnect();
await mongoServer.stop();
○ });
63. What are some useful MongoDB management tools
and libraries?
describe('User Model', () => {
○ Tools like MongoDB Atlas for cloud-based
it('should create a new user', async () => {
management, Robo 3T for GUI-based
interaction, and libraries like Mongoose for const user = new User({ name: 'John Doe',
object data modeling in Node.js. age: 30, email: '[email protected]' });
const savedUser = await user.save();
Example with Mongoose: expect(savedUser.name).to.equal('John Doe');
javascript });
Copy code });
const mongoose = require('mongoose');
○
This comprehensive list of questions and examples covers ○ Map-Reduce is a data processing paradigm
advanced topics in both backend development with Node.js and for condensing large volumes of data into
database management with MongoDB, providing a solid useful aggregated results. It involves a map
foundation for preparing for technical interviews in these areas. function to process each document and a
reduce function to combine the results.
4o
Example:
continue javascript
Copy code
ChatGPT db.orders.mapReduce(
function() { emit(this.cust_id, this.amount);
Advanced MongoDB Features },
function(key, values) { return
65. What is the aggregation framework in MongoDB? Array.sum(values); },
How does it work?
{ out: "order_totals" }
○ The aggregation framework processes data
);
records and returns computed results. It
operates on the concept of data pipelines, db.order_totals.find();
where documents are processed in stages.
○
Example:
javascript MongoDB Administration
Copy code
db.orders.aggregate([ 69. How do you monitor MongoDB performance?
{ $match: { status: "A" } }, ○ Use tools like MongoDB Cloud Manager, Ops
{ $group: { _id: "$cust_id", total: { $sum: Manager, or open-source monitoring tools
"$amount" } } }, like mongostat, mongotop, and the
{ $sort: { total: -1 } } MongoDB Profiler.
]);
Example:
shell
○
Copy code
66. How do you perform text search in MongoDB?
mongostat --host localhost --port 27017
○ MongoDB supports text search through text
indexes. You can create text indexes on fields
containing string data. ○
70. How do you perform a backup and restore of a
MongoDB database?
Example:
javascript ○ Use the mongodump and mongorestore
Copy code tools to back up and restore MongoDB
db.articles.createIndex({ title: "text", databases.
content: "text" });
Example:
db.articles.find({ $text: { $search: "mongodb
shell
tutorial" } }); Copy code
mongodump --out /data/backup/
○
mongorestore --dir /data/backup/
67. What are MongoDB change streams? How do you
use them?
○
○ Change streams allow applications to access
real-time data changes without the
complexity and risk of tailing the oplog. They MongoDB Atlas
provide a way to listen to changes on a
collection. 71. What is MongoDB Atlas? How do you deploy a
database using Atlas?
Example: ○ MongoDB Atlas is a fully-managed cloud
javascript database service. It provides automated
Copy code provisioning, patching, backups, and
const changeStream = monitoring.
db.collection('orders').watch(); ○ Example:
■ Sign up for MongoDB Atlas.
changeStream.on('change', (change) => {
■ Create a new cluster.
console.log('Change detected:', change);
■ Configure security settings (IP
}); whitelist, user roles).
■ Connect to the cluster using the
○ provided connection string.
68. Explain the Map-Reduce function in MongoDB.
When would you use it?
javascript 74. How do you handle large datasets in MongoDB?
Copy code ○ Use sharding to distribute large datasets
const { MongoClient } = require('mongodb'); across multiple servers.
const uri = "your_atlas_connection_string"; ○ Optimize queries and indexes to improve
const client = new MongoClient(uri, { performance.
○ Use the aggregation framework for complex
useNewUrlParser: true, useUnifiedTopology: true
data processing.
});
Example:
async function run() { javascript
try { Copy code
await client.connect(); sh.enableSharding("myDatabase");
const database = client.db('test'); sh.shardCollection("myDatabase.myCollection", {
const collection = shardKey: 1 });
database.collection('users');
const user = await collection.findOne({ ○
name: "John Doe" });
console.log(user); Query Optimization
} finally {
await client.close(); 75. How do you optimize MongoDB queries for
performance?
}
○ Use indexes to speed up query performance.
}
○ Analyze query performance using
explain().
run().catch(console.dir); ○ Avoid using unindexed fields in queries.
○ Optimize schema design to align with query
○ patterns.
72. How do you scale a MongoDB cluster on Atlas?
○ Scaling a MongoDB cluster on Atlas involves Example:
upgrading instance sizes, adding more javascript
shards for horizontal scaling, or enabling Copy code
auto-scaling features. db.collection.createIndex({ field1: 1, field2:
○ Example:
-1 });
■ Navigate to the Cluster page on
db.collection.find({ field1: value1
Atlas.
■ Click on the "Scale" button. }).explain("executionStats");
■ Choose the new cluster size and
configuration. ○
■ Apply changes to scale the cluster. 76. What is the $geoNear aggregation stage in
MongoDB?
MongoDB Best Practices ○ The $geoNear aggregation stage calculates
distances from a point and filters documents
73. What are some best practices for schema design in within a specified range.
MongoDB?
○ Design schema according to application Example:
requirements and query patterns. javascript
○ Prefer embedding for small sub-documents Copy code
and referencing for large or frequently db.places.aggregate([
updated documents. {
○ Avoid large documents (16MB limit) and $geoNear: {
deeply nested documents.
near: { type: "Point", coordinates: [
○ Use appropriate data types for fields.
-73.9667, 40.78 ] },
distanceField: "dist.calculated",
Example:
javascript maxDistance: 2000,
Copy code query: { type: "restaurant" },
const userSchema = { spherical: true
name: String, }
email: String, }
profile: { ]);
age: Number,
address: String ○
}
}; MongoDB Transactions
○
77. How do you implement multi-document Copy code
transactions in MongoDB? db.orders.createIndex({ status: 1, date: -1 });
○ Use sessions to start a transaction and
include multiple operations in the transaction ○
scope.
This comprehensive list of advanced MongoDB features and
Example: techniques covers essential aspects of working with MongoDB in
javascript real-world applications, providing a solid foundation for preparing
Copy code for technical interviews and improving your proficiency with
const session = client.startSession(); MongoDB.
session.startTransaction();
4o
try {
db.users.updateOne({ _id: 1 }, { $set: { continue
balance: 50 } }, { session });
db.accounts.updateOne({ _id: 2 }, { $set: { ChatGPT
balance: 150 } }, { session });
session.commitTransaction(); MongoDB Aggregation and Querying
} catch (error) {
session.abortTransaction(); 81. How do you use the $project stage in MongoDB
aggregation?
} finally {
○ The $project stage is used to include,
session.endSession();
exclude, or add new fields to documents
}
being passed through the aggregation
pipeline.
○
Example:
MongoDB Performance Monitoring javascript
Copy code
78. How do you use the MongoDB profiler? db.orders.aggregate([
○ The MongoDB profiler collects fine-grained { $project: { _id: 0, item: 1, total: {
data about MongoDB operations, such as $multiply: ["$price", "$quantity"] } } }
CRUD operations and queries.
]);
Example:
○
javascript
82. What is the $unwind stage in MongoDB
Copy code
aggregation?
db.setProfilingLevel(2);
○ The $unwind stage deconstructs an array
db.system.profile.find({ millis: { $gt: 100 }
field from the input documents to output a
}).sort({ ts: -1 });
document for each element.
○ Example:
javascript
Advanced Indexing Techniques Copy code
db.orders.aggregate([
79. What are partial indexes in MongoDB? { $unwind: "$items" },
○ Partial indexes index only a subset of { $project: { _id: 0, order_id: 1, item:
documents in a collection based on a filter
"$items.name", quantity: "$items.qty" } }
expression.
]);
Example:
javascript ○
Copy code 83. Explain the $group stage in MongoDB aggregation.
db.users.createIndex({ age: 1 }, { ○ The $group stage groups input documents
partialFilterExpression: { age: { $gt: 21 } } by a specified identifier expression and
applies the accumulator expressions to each
});
group.
○
Example:
80. What are compound indexes in MongoDB?
javascript
○ Compound indexes index multiple fields
Copy code
within a document and support more efficient
db.sales.aggregate([
queries on those fields.
{ $group: { _id: "$item", totalSales: { $sum:
Example: "$amount" }, avgQuantity: { $avg: "$quantity" }
javascript } }
]); ○
○
Example:
javascript
MongoDB Geospatial Queries Copy code
db.collection.createIndex({ user_id: "hashed"
85. How do you perform geospatial queries in });
MongoDB?
○ MongoDB supports geospatial indexes and
○
queries, allowing for operations like finding
documents near a specific location.
MongoDB Performance Tuning
Example:
javascript 89. What are some techniques to optimize MongoDB
Copy code performance?
db.places.createIndex({ location: "2dsphere" }); ○ Optimize schema design.
○ Use proper indexing.
db.places.find({
○ Perform query optimization and analysis
location: {
using explain().
$near: { ○ Use aggregation pipelines effectively.
$geometry: { type: "Point", coordinates: [
-73.9667, 40.78 ] }, Example:
$maxDistance: 1000 javascript
} Copy code
} db.orders.find({ status: "A"
}); }).explain("executionStats");
○ ○
86. Explain the use of the $geoWithin operator in 90. How do you use the $sample stage in MongoDB
MongoDB. aggregation?
○ The $geoWithin operator selects ○ The $sample stage randomly selects a
documents with geospatial data within a specified number of documents from its input.
specified geometry.
Example:
Example: javascript
javascript Copy code
Copy code db.orders.aggregate([
db.places.find({ { $sample: { size: 5 } }
location: { ]);
$geoWithin: {
$geometry: { type: "Polygon", coordinates: ○
[ [ [ -73.97, 40.77 ], [ -73.97, 40.78 ], [
-73.96, 40.78 ], [ -73.96, 40.77 ], [ -73.97, MongoDB Data Validation
40.77 ] ] ] }
} 91. How do you enforce data validation in MongoDB?
○ Use schema validation rules to enforce data
}
integrity in collections.
});
Example: 94. Explain the $elemMatch operator in MongoDB.
javascript ○ The $elemMatch operator matches
Copy code documents that contain an array field with at
db.createCollection("users", { least one element that matches all the
validator: { specified query criteria.
$jsonSchema: {
bsonType: "object", Example:
required: [ "name", "email" ], javascript
Copy code
properties: {
db.inventory.find({
name: { bsonType: "string" },
items: { $elemMatch: { qty: { $gt: 10, $lt: 20
email: { bsonType: "string", pattern:
} } }
"^.+@.+$" }
});
}
}
○
}
95. How do you use the $regex operator in MongoDB?
});
○ The $regex operator provides regular
expression capabilities for pattern matching
○
strings in queries.
92. Explain how to use custom validation in MongoDB.
○ Custom validation involves using JavaScript
Example:
functions to enforce complex validation rules.
javascript
Copy code
Example:
db.users.find({ name: { $regex: /^A/, $options:
javascript
Copy code 'i' } });
db.runCommand({
○
collMod: "users",
validator: {
$jsonSchema: { MongoDB Schema Design Patterns
bsonType: "object",
96. What are some common schema design patterns in
required: [ "name", "email" ],
MongoDB?
properties: { ○ Single View Pattern: Aggregating data from
name: { bsonType: "string" }, multiple sources into a single document.
email: { bsonType: "string", pattern: ○ Tree Pattern: Using parent references, child
"^.+@.+$" } references, or materialized paths to represent
} hierarchical data.
○ Subset Pattern: Storing frequently accessed
}
data in the same document to reduce the
},
number of reads.
validationAction: "warn"
}); Example:
javascript
○ Copy code
const userSchema = {
MongoDB Data Migration name: String,
email: String,
93. How do you handle data migrations in MongoDB? profile: {
○ Use tools like mongodump and age: Number,
mongorestore, or use the MongoDB Atlas address: String
Data Lake. },
○ Plan schema changes carefully and use
orders: [{ order_id: String, amount: Number }]
scripts or tools for data migration.
};
Example:
shell ○
Copy code
mongodump --uri mongodb://localhost:27017/mydb MongoDB GridFS
--out /data/backup/
mongorestore --uri mongodb://newhost:27017/mydb 97. What is GridFS in MongoDB? How do you use it?
○ GridFS is a specification for storing and
--dir /data/backup/
retrieving large files (larger than the
BSON-document size limit of 16 MB).
○
Example:
javascript
Copy code
db.collection.createIndex({ field: 1 });
db.collection.find({ field: value
}).explain("executionStats");
○
99. How do you ensure data consistency and integrity
in MongoDB?
○ Use transactions for multi-document
operations.
○ Implement schema validation.
○ Regularly back up and test data recovery
processes.
Example:
javascript
Copy code
const session = client.startSession();
session.startTransaction();
try {
db.collection1.updateOne({ _id: 1 }, { $set: {
field: value } }, { session });
db.collection2.updateOne({ _id: 1 }, { $set: {
field: value } }, { session });
session.commitTransaction();
} catch (error) {
session.abortTransaction();
} finally {
session.endSession();
}