MongoDB’s document model removes most of the schema ceremony that comes with relational databases, but it introduces its own rules around data modeling, indexing, and querying. If you come from SQL and just wing it, you will end up with queries that are slow for reasons that aren’t obvious at all.
TL;DR: A practical MongoDB reference covering installation, connection, data modeling, and querying including the aggregation pipeline.
Stack: MongoDB, Docker, mongo shell
Level: Beginner
Reading time: ~7 min
Installing and connecting on Ubuntu
The fastest way to get MongoDB running locally is via Docker. No repository setup, spin it up in seconds.
# Start new instance
docker run --name local_mongo -d -p 27017:27017 -p 28017:28017 -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=123123 mongo
# Connection string (works on MongoDB Compass)
"mongodb://admin:123123@localhost:27017/?authSource=admin"
Example complex collection
[
{
"itemId": "1234567890",
"itemName": "Laptop XYZ",
"category": "Electronics",
"price": 999.99,
"inventory": [
{ "warehouse": "A", "quantity": 50 },
{ "warehouse": "B", "quantity": 25 }
],
"reviews": [
{ "userId": "user123", "rating": 5, "comment": "Excellent product!" },
{ "userId": "user456", "rating": 4, "comment": "Good, but battery could last longer." }
],
"sales": [
{ "date": "2023-10-26", "quantity": 10, "price": 999.99 },
{ "date": "2023-10-27", "quantity": 5, "price": 949.99 }
]
}
]
Query examples
// Simple query by field on 1st level
db.products.find({ category: "Electronics" })
// Combining conditions
db.products.find({
$and: [
{ "inventory.warehouse": "A" },
{ "inventory.quantity": { $gt: 50 } }
]
})
// Partial text match
db.products.find({ itemName: { $regex: "Smart" } })
// Aggregating and summing
db.products.aggregate([
{ $unwind: "$inventory" },
{
$group: {
_id: "$itemId",
totalQuantity: { $sum: "$inventory.quantity" }
}
}
])
What you’ve built
A working MongoDB reference: how to spin up a local instance, insert nested documents, and query them with filters, regex, and the aggregation pipeline. The aggregation examples cover the two operations that trip people up most often when coming from SQL: $unwind for arrays and $group for summaries.
Next steps
- Add indexes to the fields you query most. MongoDB will happily scan every document without them, and at scale that hurts. Start with
db.collection.createIndex({ field: 1 })and useexplain()to verify indexes are being hit. - Explore the change streams API if you need to react to database changes in real time without polling.
- Connect from Python using pymongo or motor (async) and replicate these queries programmatically.
Questions or feedback? Find me on LinkedIn or GitHub.