MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It's designed for scalability, performance, and developer productivity.
MongoDB stores data in BSON (Binary JSON) documents. Here's an example:
{
"_id": ObjectId("..."),
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
},
"interests": ["reading", "music", "sports"]
}
Collections are groups of documents, similar to tables in relational databases.
// Create a collection
db.createCollection("users")
// Insert a document
db.users.insertOne({
name: "John Doe",
age: 30
})
MongoDB databases are containers for collections.
// Switch to a database
use myDatabase
// List all databases
show dbs
// List all collections
show collections
// Insert a single document
db.users.insertOne({
name: "John Doe",
age: 30
})
// Insert multiple documents
db.users.insertMany([
{ name: "Jane Doe", age: 25 },
{ name: "Bob Smith", age: 35 }
])
// Find all documents
db.users.find()
// Find with a filter
db.users.find({ age: { $gt: 25 } })
// Find one document
db.users.findOne({ name: "John Doe" })
Now that you understand the basics of MongoDB, you can explore: