Skip to main content

CRUD operations and queries

 

CRUD Operations and Queries in MongoDB


1. Introduction

CRUD stands for:

  • Create

  • Read

  • Update

  • Delete

MongoDB performs CRUD operations on documents stored inside collections.


2. Create Operation (Insert)

Used to add new documents to a collection.

Commands

  • insertOne() – insert one document

  • insertMany() – insert multiple documents

Example

db.students.insertOne({ name: "Amit", age: 21, course: "MCA" })

3. Read Operation (Find)

Used to retrieve documents from a collection.

Commands

  • find() – fetch all matching documents

  • findOne() – fetch a single document

Example

db.students.find({ course: "MCA" })

Query Operators

  • $gt – greater than

  • $lt – less than

  • $eq – equal

db.students.find({ age: { $gt: 20 } })

4. Update Operation

Used to modify existing documents.

Commands

  • updateOne()

  • updateMany()

Update Operators

  • $set – update a field

  • $inc – increment value

Example

db.students.updateOne( { name: "Amit" }, { $set: { age: 22 } } )

5. Delete Operation

Used to remove documents from a collection.

Commands

  • deleteOne()

  • deleteMany()

Example

db.students.deleteOne({ name: "Amit" })

6. Query Features in MongoDB

MongoDB provides powerful querying features:

Filtering

db.students.find({ age: 21 })

Sorting

db.students.find().sort({ age: 1 })

Limiting Results

db.students.find().limit(5)

7. Aggregation (Basic Idea)

Used for data analysis and reporting.

Example

db.students.aggregate([ { $group: { _id: "$course", total: { $sum: 1 } } } ])

8. Advantages of MongoDB CRUD Operations

  • Simple and easy syntax

  • JSON-based queries

  • High performance

  • Flexible data handling

Comments