MongoDB Setup and CRUD Operations Tutorial For Begniers
MongoDB Setup and CRUD Operations Tutorial For Begniers
Contents
1 Introduction 2
2 Prerequisites 2
3 Setting Up MongoDB 2
3.1 Local Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3.2 MongoDB Atlas (Cloud) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
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
or for Atlas:
mongosh ”mongodb+srv://<username>:<password>@cluster0.xxx.mongodb.net/”
2
Output includes an auto-generated _id:
{
”acknowledged”: true,
”insertedId”: ObjectId(”6718b3a2e4b0c3f1a2b3c4d5”)
}
5.2 Read
Retrieve all documents:
db.tutorials.find().pretty()
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 } }
)
3
5.4 Delete
Delete a single document:
db.tutorials.deleteOne({ title: ”Python MongoDB” })
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);
}
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);
}
}
5
8 Best Practices
• Use environment variables for sensitive data like MongoDB credentials.
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/