MongoDB is a popular NoSQL database that provides high performance, high availability, and easy scalability. To interact with MongoDB from your application, you need a driver that allows your programming language to communicate with the MongoDB server. This tutorial covers the basics of using MongoDB drivers in various programming languages, focusing on common operations such as connecting to the database, inserting documents, querying data, updating documents, and deleting documents.
Before diving into the details, ensure you have the following:
To connect to MongoDB using Node.js, you need the mongodb package. Install it using npm:
npm install mongodb
Here's how to establish a connection:
const { MongoClient } = require('mongodb');
async function main() {
const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);
try {
await client.connect();
console.log("Connected successfully to server");
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
main().catch(console.error);
For Python, use the pymongo package:
pip install pymongo
Here's how to connect:
from pymongo import MongoClient
client = MongoClient('your_mongodb_connection_string')
db = client['your_database_name']
collection = db['your_collection_name']
print("Connected successfully")
For Java, use the MongoDB Java Driver:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.3.1</version>
</dependency>
Here's how to connect:
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDBExample {
public static void main(String[] args) {
MongoClient mongoClient = MongoClients.create("your_mongodb_connection_string");
MongoDatabase database = mongoClient.getDatabase("your_database_name");
System.out.println("Connected successfully to server");
}
}
const insertDocuments = async () => {
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('your_database_name');
const collection = database.collection('your_collection_name');
const docs = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount} documents were inserted`);
} finally {
await client.close();
}
};
insertDocuments().catch(console.error);
from pymongo import MongoClient
client = MongoClient('your_mongodb_connection_string')
db = client['your_database_name']
collection = db['your_collection_name']
docs = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
result = collection.insert_many(docs)
print(f"{len(result.inserted_ids)} documents were inserted")
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class InsertDocuments {
public static void main(String[] args) {
MongoClient mongoClient = MongoClients.create("your_mongodb_connection_string");
MongoDatabase database = mongoClient.getDatabase("your_database_name");
MongoCollection<Document> collection = database.getCollection("your_collection_name");
Document doc1 = new Document("name", "Alice").append("age", 30);
Document doc2 = new Document("name", "Bob").append("age", 25);
collection.insertMany(Arrays.asList(doc1, doc2));
System.out.println("Documents inserted successfully");
}
}
const findDocuments = async () => {
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('your_database_name');
const collection = database.collection('your_collection_name');
const query = { age: { $gt: 25 } };
const cursor = collection.find(query);
await cursor.forEach(doc => console.log(doc));
} finally {
await client.close();
}
};
findDocuments().catch(console.error);
from pymongo import MongoClient
client = MongoClient('your_mongodb_connection_string')
db = client['your_database_name']
collection = db['your_collection_name']
query = {"age": {"$gt": 25}}
for doc in collection.find(query):
print(doc)
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class QueryDocuments {
public static void main(String[] args) {
MongoClient mongoClient = MongoClients.create("your_mongodb_connection_string");
MongoDatabase database = mongoClient.getDatabase("your_database_name");
MongoCollection<Document> collection = database.getCollection("your_collection_name");
Document query = new Document("age", new Document("$gt", 25));
for (Document doc : collection.find(query)) {
System.out.println(doc.toJson());
}
}
}
const updateDocuments = async () => {
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('your_database_name');
const collection = database.collection('your_collection_name');
const filter = { name: "Alice" };
const updateDoc = {
$set: {
age: 31
}
};
const result = await collection.updateOne(filter, updateDoc);
console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`);
} finally {
await client.close();
}
};
updateDocuments().catch(console.error);
from pymongo import MongoClient
client = MongoClient('your_mongodb_connection_string')
db = client['your_database_name']
collection = db['your_collection_name']
filter = {"name": "Alice"}
new_values = { "$set": { "age": 31 } }
result = collection.update_one(filter, new_values)
print(f"Matched {result.matched_count} document(s), updated {result.modified_count} document(s)")
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class UpdateDocuments {
public static void main(String[] args) {
MongoClient mongoClient = MongoClients.create("your_mongodb_connection_string");
MongoDatabase database = mongoClient.getDatabase("your_database_name");
MongoCollection<Document> collection = database.getCollection("your_collection_name");
Document filter = new Document("name", "Alice");
Document updateDoc = new Document("$set", new Document("age", 31));
collection.updateOne(filter, updateDoc);
System.out.println("Document updated successfully");
}
}
const deleteDocuments = async () => {
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('your_database_name');
const collection = database.collection('your_collection_name');
const filter = { name: "Bob" };
const result = await collection.deleteOne(filter);
console.log(`${result.deletedCount} document(s) were deleted`);
} finally {
await client.close();
}
};
deleteDocuments().catch(console.error);
from pymongo import MongoClient
client = MongoClient('your_mongodb_connection_string')
db = client['your_database_name']
collection = db['your_collection_name']
filter = {"name": "Bob"}
result = collection.delete_one(filter)
print(f"{result.deleted_count} document(s) were deleted")
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class DeleteDocuments {
public static void main(String[] args) {
MongoClient mongoClient = MongoClients.create("your_mongodb_connection_string");
MongoDatabase database = mongoClient.getDatabase("your_database_name");
MongoCollection<Document> collection = database.getCollection("your_collection_name");
Document filter = new Document("name", "Bob");
collection.deleteOne(filter);
System.out.println("Document deleted successfully");
}
}
This tutorial covered the basics of using MongoDB drivers in JavaScript/Node.js, Python, and Java. You learned how to connect to a MongoDB database, perform CRUD operations, and apply best practices for efficient and secure database interactions. For more advanced features and capabilities, refer to the official MongoDB documentation for your specific driver.