[go: up one dir, main page]

0% found this document useful (0 votes)
8 views6 pages

MongoDB Setup and CRUD Operations Tutorial For Begniers

Uploaded by

tricka325
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

MongoDB Setup and CRUD Operations Tutorial For Begniers

Uploaded by

tricka325
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

MongoDB Setup and CRUD Operations Tutorial

September 30, 2025

Contents
1 Introduction 2

2 Prerequisites 2

3 Setting Up MongoDB 2
3.1 Local Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3.2 MongoDB Atlas (Cloud) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

4 Creating a Database and Collection 2

5 CRUD Operations in MongoDB Shell 3


5.1 Create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
5.2 Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
5.3 Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
5.4 Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

6 Integrating MongoDB with Spring Boot 4


6.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
6.2 Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
6.3 Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
6.4 REST Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

7 Testing the Application 5

8 Best Practices 6

9 Conclusion 6

10 References 6

1
1 Introduction
This tutorial provides a comprehensive guide to setting up MongoDB, performing CRUD
operations using the MongoDB shell, and integrating MongoDB with a Spring Boot appli-
cation for a RESTful API. MongoDB is a NoSQL, document-oriented database that stores
data in JSON-like BSON documents, offering flexibility and scalability.

2 Prerequisites
To follow this tutorial, ensure you have:
• MongoDB Community Edition installed locally or a MongoDB Atlas cloud account.
• MongoDB Shell (mongosh) for command-line operations.
• Optional: MongoDB Compass for GUI-based data visualization.
• Java 17+, Maven, and a Spring Boot project for integration.

3 Setting Up MongoDB
3.1 Local Installation
Download MongoDB Community Edition from https://www.mongodb.com/try/download/
community. Start the server:
mongod

3.2 MongoDB Atlas (Cloud)


1. Sign up at https://www.mongodb.com/atlas.
2. Create a free cluster, add a database user, and whitelist your IP.
3. Obtain the connection string, e.g., mongodb+srv://<username>:<password>@cluster0.xxx.m

Connect using mongosh:


mongosh ”mongodb://localhost:27017”

or for Atlas:
mongosh ”mongodb+srv://<username>:<password>@cluster0.xxx.mongodb.net/”

4 Creating a Database and Collection


Switch to a database (created automatically upon use):
use tutorialdb

Insert a document to create the tutorials collection:


db.tutorials.insertOne({
title: ”MongoDB Tutorial”,
description: ”Learn MongoDB basics”,
published: true
})

2
Output includes an auto-generated _id:
{
”acknowledged”: true,
”insertedId”: ObjectId(”6718b3a2e4b0c3f1a2b3c4d5”)
}

5 CRUD Operations in MongoDB Shell


5.1 Create
Insert a single document:
db.tutorials.insertOne({
title: ”Spring Boot with MongoDB”,
description: ”Build a REST API”,
published: false
})

Insert multiple documents:


db.tutorials.insertMany([
{ title: ”Node.js with MongoDB”, description: ”Backend tutorial”,
published: true },
{ title: ”Python MongoDB”, description: ”Data analysis”, published:
false }
])

5.2 Read
Retrieve all documents:
db.tutorials.find().pretty()

Find a specific document:


db.tutorials.findOne({ title: ”MongoDB Tutorial” })

Filter by condition:
db.tutorials.find({ published: true }).pretty()

5.3 Update
Update a single document:
db.tutorials.updateOne(
{ title: ”MongoDB Tutorial” },
{ $set: { description: ”Updated MongoDB basics”, published: false } }
)

Update multiple documents:


db.tutorials.updateMany(
{ published: false },
{ $set: { published: true } }
)

3
5.4 Delete
Delete a single document:
db.tutorials.deleteOne({ title: ”Python MongoDB” })

Delete multiple documents:


db.tutorials.deleteMany({ published: false })

6 Integrating MongoDB with Spring Boot


This section assumes a Spring Boot project with spring-boot-starter-data-mongodb
and spring-boot-starter-web dependencies.

6.1 Configuration
In src/main/resources/application.properties, configure the MongoDB connec-
tion:
spring.data.mongodb.uri=mongodb+srv://<username>:<password>@cluster0.xxx.
mongodb.net/tutorialdb?retryWrites=true&w=majority

6.2 Model
Define the Tutorial entity:
@Document(collection = ”tutorials”)
public class Tutorial {
@Id
private String id;
private String title;
private String description;
private boolean published;
// Constructors, getters, setters
}

6.3 Repository
Create a repository interface:
@Repository
public interface TutorialRepository extends MongoRepository<Tutorial,
String> {
List<Tutorial> findByPublished(boolean published);
List<Tutorial> findByTitleContaining(String title);
}

6.4 REST Controller


Define endpoints for CRUD operations:
@RestController
@RequestMapping(”/api/tutorials”)
public class TutorialController {
@Autowired

4
private TutorialService tutorialService;

@PostMapping
public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial
tutorial) {
Tutorial savedTutorial = tutorialService.createTutorial(tutorial);
return new ResponseEntity<>(savedTutorial, HttpStatus.CREATED);
}

@GetMapping
public ResponseEntity<List<Tutorial>> getAllTutorials() {
List<Tutorial> tutorials = tutorialService.getAllTutorials();
return new ResponseEntity<>(tutorials, HttpStatus.OK);
}

@GetMapping(”/{id}”)
public ResponseEntity<Tutorial> getTutorialById(@PathVariable String id
) {
Tutorial tutorial = tutorialService.getTutorialById(id).orElseThrow
(() -> new RuntimeException(”Tutorial␣not␣found”));
return new ResponseEntity<>(tutorial, HttpStatus.OK);
}

@PutMapping(”/{id}”)
public ResponseEntity<Tutorial> updateTutorial(@PathVariable String id,
@RequestBody Tutorial tutorial) {
Tutorial updatedTutorial = tutorialService.updateTutorial(id,
tutorial);
return new ResponseEntity<>(updatedTutorial, HttpStatus.OK);
}

@DeleteMapping(”/{id}”)
public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable String
id) {
tutorialService.deleteTutorial(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

7 Testing the Application


Run the Spring Boot application:
./mvnw spring-boot:run

Test endpoints using Postman or curl:

• Create: POST http://localhost:8080/api/tutorials

• Read: GET http://localhost:8080/api/tutorials

• Update: PUT http://localhost:8080/api/tutorials/{id}

• Delete: DELETE http://localhost:8080/api/tutorials/{id}

Verify data in MongoDB using mongosh or MongoDB Compass.

5
8 Best Practices
• Use environment variables for sensitive data like MongoDB credentials.

• Implement error handling with @ControllerAdvice in Spring Boot.

• Design efficient document schemas to avoid frequent updates to large arrays.

• Use indexes to improve query performance, e.g.:


db.tutorials.createIndex({ title: 1 })

9 Conclusion
This tutorial covered setting up MongoDB, performing CRUD operations in the Mon-
goDB shell, and integrating MongoDB with Spring Boot for a REST API. For further learn-
ing, explore MongoDB’s aggregation framework or reactive programming with Spring
WebFlux.

10 References
• MongoDB Documentation: https://docs.mongodb.com/

• Spring Data MongoDB: https://spring.io/projects/spring-data-mongodb

You might also like