Define NoSQL Databases. List Different Types of NoSQL Databases. Also Explain Pros and Cons
Definition of NoSQL
NoSQL stands for “Not Only SQL.” It refers to database management systems that store and retrieve data using models other than the traditional row-and-column table structure of relational databases.
NoSQL databases generally provide a flexible/schema-less structure, support horizontal scaling, handle large amounts of unstructured data, and are designed for high-speed distributed systems.
Types of NoSQL Databases
There are four major types:
| Type | Description | Examples |
|---|---|---|
| Document-Oriented | Stores data as flexible JSON/BSON-like documents | MongoDB, CouchDB |
| Key-Value | Stores data as simple key-value pairs | Redis, DynamoDB |
| Column-Family | Stores data in columns grouped into families | Cassandra, HBase |
| Graph Database | Stores entities as nodes and relationships as edges | Neo4j, ArangoDB |
Advantages (Pros) of NoSQL
Disadvantages (Cons) of NoSQL
Explain the Features of NoSQL Databases
NoSQL databases provide several architectural features that make them suitable for large-scale, distributed, and flexible applications.
Explain CRUD Operations in MongoDB with Syntax and Examples
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations used to manage data in MongoDB.
MongoDB provides insertOne() to insert one document and insertMany() to insert multiple documents. If _id is not provided, MongoDB automatically generates a unique ObjectId.
db.collectionName.insertOne(document)Exampledb.students.insertOne({
name: "Riya Shah",
age: 20,
course: "BCA"
})insertMany() exampledb.students.insertMany([
{ name: "Aman", age: 21 },
{ name: "Priya", age: 22 }
])The find() method retrieves documents from a collection. A condition can be provided to filter the results.
db.collectionName.find({ condition })Exampledb.students.find({ course: "BCA" })findOne() can be used when only one matching document is required.
db.students.findOne({ name: "Riya" })Query operators can also be used:
db.students.find({ age: { $gt: 18 } })Here, $gt means greater than.
updateOne() modifies the first matching document, while updateMany() modifies all matching documents.
db.students.updateOne(
{ name: "Riya Shah" },
{ $set: { age: 21 } }
)updateMany() exampledb.students.updateMany(
{ course: "BCA" },
{ $set: { year: 2026 } }
)Common update operators include $set, $unset, $inc, $rename, $push, and $pull.
deleteOne() removes the first matching document, while deleteMany() removes all documents matching the condition. Deleted documents cannot be automatically undone, so the filter should be used carefully.
db.students.deleteOne(
{ name: "Karan Joshi" }
)deleteMany() exampledb.students.deleteMany(
{ course: "BCA" }
)Explain MongoDB Aggregation Framework in Detail
The Aggregation Framework in MongoDB is used to process documents and return computed results. It works using an aggregation pipeline, where documents pass through a sequence of stages. Each stage performs an operation and passes its output to the next stage.
It is useful for operations such as filtering, grouping, calculating totals/averages, reshaping documents, sorting, and joining collections.
Basic syntaxdb.collection.aggregate([
{ stage1 },
{ stage2 },
...
])
db.students.aggregate([
{ $match: { course: "BCA" } },
{ $sort: { marks: -1 } },
{ $limit: 2 },
{ $project: { _id: 0, name: 1, marks: 1 } }
])
Explain Update Operators in MongoDB with Examples
Update operators in MongoDB are used with methods such as updateOne() and updateMany() to modify specific fields of existing documents without replacing the entire document.
{ upsert: true } is specified, if a matching document exists it is updated, and if no matching document exists a new document is created.| Operator | Function |
|---|---|
| $set | Set/add a field |
| $unset | Remove a field |
| $inc | Increase/decrease numeric value |
| $mul | Multiply numeric value |
| $push | Add element to array |
| $pull | Remove element from array |
| $addToSet | Add unique element to array |
| upsert | Update if found, insert if not found |
Compare SQL and NoSQL Databases
SQL databases are relational databases that store data in structured tables and rows, whereas NoSQL databases can store data using documents, key-value pairs, graphs, or column-family models.
| Basis | SQL Database | NoSQL Database |
|---|---|---|
| Schema | Uses a fixed, predefined schema. All rows follow the defined table structure. | Uses a flexible/schema-less structure. Documents can have different fields and structures. |
| Scalability | Mainly uses vertical scaling (scale-up) by increasing CPU, RAM, etc. of a server. | Designed for horizontal scaling (scale-out) by adding more servers using techniques such as sharding. |
| Consistency | Generally follows the ACID model, providing strong consistency and reliable transactions. | Generally follows the BASE model and may use eventual consistency to provide greater availability and scalability. |
| Use Cases | Suitable when data is highly structured and reliable transactions/consistency are important. | Suitable for big data, rapidly changing data, unstructured/semi-structured data, web/mobile applications and IoT. |
| Examples | MySQL, Oracle | MongoDB, Redis, Cassandra |
Explanation of Major Differences
Explain Projection Operators with Example
Projection operators in MongoDB are used to control which fields or portions of data are returned from a query. They are generally used as the second argument of the find() method. While basic projection using 1 and 0 selects or excludes top-level fields, projection operators provide finer control, especially when working with array fields.
The main projection operators covered here are $slice, $ (positional operator) and $elemMatch.
The $slice operator is used to return only a specified number of elements from an array instead of returning the complete array.
db.students.find({}, { subjects: { $slice: 2 } })
Last 2 elementsdb.students.find({}, { subjects: { $slice: -2 } })
Skip 1 element, take the next 2db.students.find({}, { subjects: { $slice: [1, 2] } })
This is useful when an array contains many elements but the application needs only a small portion of them.
The positional $ operator returns only the first array element that matches the query condition.
db.students.find(
{ subjects: "Math" },
{ "subjects.$": 1 }
)
Here, MongoDB searches for students whose subjects array contains "Math" and returns only the first matching element from that array.
The $elemMatch projection operator returns the first array element that satisfies a specified condition.
db.students.find(
{ "scores": { $elemMatch: { $gt: 80 } } },
{ "scores.$": 1 }
)
This finds students having a score greater than 80 and returns the matching array element.
| Operator | Purpose |
|---|---|
| $slice | Returns a specified portion/number of array elements |
| $ | Returns the first array element matching the query |
| $elemMatch | Returns an array element matching a specified condition |
Explain MongoDB Data Types
MongoDB stores documents in BSON (Binary JSON) format. BSON supports a richer set of data types than ordinary JSON, including different numeric types, dates, ObjectId, binary data, and other special types. Choosing the correct data type is important because it affects storage, comparisons, queries, and the operators that can be applied.
Main MongoDB Data Types
| Type | Description | Example |
|---|---|---|
| String | Stores UTF-8 encoded text. | { name: "Alice" } |
| Integer | Stores whole numbers. MongoDB supports 32-bit and 64-bit integers. | { age: 25 } |
| Double | Stores floating-point/decimal numbers. | { price: 49.99 } |
| Decimal128 | Stores high-precision decimal values, especially useful for financial calculations. | { amount: NumberDecimal("10.50") } |
| Boolean | Stores either true or false. | { active: true } |
| Date | Stores date and time as milliseconds since the Unix epoch. | { dob: ISODate("2000-01-01") } |
| ObjectId | A unique 12-byte identifier, commonly auto-generated for a document's _id field. | { _id: ObjectId("...") } |
| Array | Stores an ordered list of values; the values can be of different types. | { tags: ["html", "css"] } |
| Object / Embedded Document | Stores a document inside another document. | { address: { city: "Ahmedabad" } } |
| Null | Represents a null or missing value. | { phone: null } |
| Regular Expression | Stores a pattern used for pattern matching. | { pattern: /^A/i } |
| Binary Data | Stores binary content such as images or files. | { file: BinData(0, "...") } |
| JavaScript | Stores JavaScript code as a value. | { fn: function(){...} } |
| Timestamp | A special MongoDB timestamp used internally, particularly for replication. | { ts: Timestamp(0, 1) } |
| MinKey / MaxKey | Special BSON types used for comparison purposes to represent the minimum and maximum values. | — |
{
_id: ObjectId("64f1a2..."),
name: "Riya Shah",
age: 20,
isActive: true,
course: "BCA",
marks: [88, 92, 79],
address: {
city: "Vadodara",
pincode: 390001
},
enrolledOn: ISODate("2025-07-01")
}
Here, the document demonstrates ObjectId, String, Integer, Boolean, Array, Embedded Object and Date data types.