MongoDB CRUD
This guide demonstrates how to perform Create, Read, Update, and Delete (CRUD) operations in MongoDB. The examples cover commonly used programming languages: JavaScript (Node.js), Python, Java, and Go.
1. Create (Insert)
The insertOne or insertMany method is used to add documents to a MongoDB collection.
Mongo Shell
use testdb;
db.users.insertOne({
name: "John Doe",
email: "john.doe@example.com",
age: 30,
active: true
});
Examples by language:
JavaScript (Node.js)
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function createDocument() {
const database = client.db("testdb");
const collection = database.collection("users");
const result = await collection.insertOne({
name: "John Doe",
email: "john.doe@example.com",
age: 30,
active: true
});
console.log("Inserted Document:", result.insertedId);
}
createDocument().catch(console.error);
Python
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client.testdb
collection = db.users
document = {
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30,
"active": True
}
result = collection.insert_one(document)
print("Inserted Document ID:", result.inserted_id)
Java
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
public class MongoDBInsert {
public static void main(String[] args) {
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("testdb");
MongoCollection<Document> collection = database.getCollection("users");
Document document = new Document("name", "John Doe")
.append("email", "john.doe@example.com")
.append("age", 30)
.append("active", true);
collection.insertOne(document);
System.out.println("Document inserted successfully");
}
}
Go
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
panic(err)
}
collection := client.Database("testdb").Collection("users")
document := bson.D{
{"name", "John Doe"},
{"email", "john.doe@example.com"},
{"age", 30},
{"active", true},
}
result, err := collection.InsertOne(ctx, document)
if err != nil {
panic(err)
}
fmt.Println("Inserted Document ID:", result.InsertedID)
}
2. Read (Retrieve)
The find method retrieves documents from a collection.
Mongo Shell
db.users.find({ active: true }).pretty();
Examples by language:
JavaScript (Node.js)
async function readDocuments() {
const database = client.db("testdb");
const collection = database.collection("users");
const documents = await collection.find({ active: true }).toArray();
console.log("Documents:", documents);
}
readDocuments().catch(console.error);
Python
documents = collection.find({"active": True})
for doc in documents:
print(doc)
Java
for (Document doc : collection.find(new Document("active", true))) {
System.out.println(doc.toJson());
}
Go
cursor, err := collection.Find(ctx, bson.M{"active": true})
if err != nil {
panic(err)
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var result bson.M
if err = cursor.Decode(&result); err != nil {
panic(err)
}
fmt.Println(result)
}
3. Update
The updateOne or updateMany method modifies existing documents.
Mongo Shell
db.users.updateOne(
{ email: "john.doe@example.com" },
{ $set: { active: false } }
);
Examples by language:
JavaScript (Node.js)
async function updateDocument() {
const database = client.db("testdb");
const collection = database.collection("users");
const result = await collection.updateOne(
{ email: "john.doe@example.com" },
{ $set: { active: false } }
);
console.log("Matched Count:", result.matchedCount);
}
updateDocument().catch(console.error);
Python
result = collection.update_one(
{"email": "john.doe@example.com"},
{"$set": {"active": False}}
)
print("Matched Count:", result.matched_count)
Java
collection.updateOne(
new Document("email", "john.doe@example.com"),
new Document("$set", new Document("active", false))
);
Go
_, err = collection.UpdateOne(
ctx,
bson.M{"email": "john.doe@example.com"},
bson.M{"$set": bson.M{"active": false}},
)
if err != nil {
panic(err)
}
4. Delete
The deleteOne or deleteMany method removes documents from a collection.
Mongo Shell
db.users.deleteOne({ email: "john.doe@example.com" });
Examples by language:
JavaScript (Node.js)
async function deleteDocument() {
const database = client.db("testdb");
const collection = database.collection("users");
const result = await collection.deleteOne({ email: "john.doe@example.com" });
console.log("Deleted Count:", result.deletedCount);
}
deleteDocument().catch(console.error);
Python
result = collection.delete_one({"email": "john.doe@example.com"})
print("Deleted Count:", result.deleted_count)
Java
collection.deleteOne(new Document("email", "john.doe@example.com"));
Go
_, err = collection.DeleteOne(ctx, bson.M{"email": "john.doe@example.com"})
if err != nil {
panic(err)
}
Notable libraries and example projects
Explore key tools and real-world examples for building CRUD applications with MongoDB:
- MongoDB Python Driver - Official Python driver for MongoDB
- Spring Boot MongoDB React Java CRUD - Full-stack CRUD application with Spring Boot, MongoDB, and React
- NodeJS MongoDB CRUD Application - Example of CRUD operations using Node.js and MongoDB
- NestJS GraphQL Best Practice - CRUD API example using NestJS and GraphQL with MongoDB support