NarvikHub Logo

NARVIKHUB

Tools

Mongodb Nosql Database

Database

2024-08-29

MongoDB NoSQL Database: Document-Based Data Management

Master MongoDB for scalable NoSQL applications, including schema design, aggregation, indexing, and replication.

MongoDBNoSQLDatabaseBackend

MongoDB is a leading NoSQL database that stores data in flexible, JSON-like documents. This guide covers MongoDB fundamentals, schema design patterns, aggregation pipelines, performance optimization, and scaling strategies.

MongoDB Basics

// Connect to MongoDB

const { MongoClient } = require('mongodb');

const uri = 'mongodb://localhost:27017';

const client = new MongoClient(uri);

// Basic CRUD operations

async function runOperations() {

await client.connect();

const db = client.db('myapp');

const users = db.collection('users');

// Insert

await users.insertOne({

name: 'John Doe',

email: 'john@example.com',

age: 30,

interests: ['coding', 'reading'],

createdAt: new Date()

});

// Find

const user = await users.findOne({ email: 'john@example.com' });

// Update

await users.updateOne(

{ email: 'john@example.com' },

{ $set: { age: 31 }, $push: { interests: 'gaming' } }

);

// Delete

await users.deleteOne({ email: 'old@example.com' });

}

Schema Design Patterns

Embedded Documents

// One-to-Few: Embed directly

{

_id: ObjectId("..."),

name: "Blog Post",

author: "John Doe",

comments: [

{ user: "Alice", text: "Great post!", date: ISODate(...) },

{ user: "Bob", text: "Thanks!", date: ISODate(...) }

]

}

// One-to-Many: Hybrid approach

{

_id: ObjectId("..."),

name: "Product",

price: 99.99,

// Embed frequently accessed data

topReviews: [

{ rating: 5, summary: "Excellent!" }

],

// Reference for full list

reviewIds: [ObjectId("..."), ObjectId("...")]

}

Reference Pattern

// Many-to-Many: Use references

// Users collection

{

_id: ObjectId("user1"),

name: "John Doe",

courseIds: [ObjectId("course1"), ObjectId("course2")]

}

// Courses collection

{

_id: ObjectId("course1"),

title: "MongoDB Basics",

studentIds: [ObjectId("user1"), ObjectId("user2")]

}

// Lookup with aggregation

db.users.aggregate([

{ $match: { _id: ObjectId("user1") } },

{ $lookup: {

from: "courses",

localField: "courseIds",

foreignField: "_id",

as: "courses"

} }

])

Aggregation Pipeline

Powerful data processing with aggregation:

db.orders.aggregate([

// Stage 1: Filter

{ $match: {

status: "completed",

date: { $gte: ISODate("2024-01-01") }

} },

// Stage 2: Join with customers

{ $lookup: {

from: "customers",

localField: "customerId",

foreignField: "_id",

as: "customer"

} },

// Stage 3: Unwind array

{ $unwind: "$customer" },

// Stage 4: Group and calculate

{ $group: {

_id: "$customer.country",

totalSales: { $sum: "$amount" },

avgOrderValue: { $avg: "$amount" },

orderCount: { $sum: 1 }

} },

// Stage 5: Sort results

{ $sort: { totalSales: -1 } },

// Stage 6: Limit results

{ $limit: 10 },

// Stage 7: Project final shape

{ $project: {

country: "$_id",

totalSales: { $round: ["$totalSales", 2] },

avgOrderValue: { $round: ["$avgOrderValue", 2] },

orderCount: 1,

_id: 0

} }

])

Indexing Strategies

// Single field index

db.users.createIndex({ email: 1 })

// Compound index

db.posts.createIndex({ author: 1, createdAt: -1 })

// Text index for search

db.articles.createIndex({ title: "text", content: "text" })

// Geospatial index

db.locations.createIndex({ location: "2dsphere" })

// Partial index (conditional)

db.orders.createIndex(

{ customerId: 1 },

{ partialFilterExpression: { status: "active" } }

)

// TTL index for automatic deletion

db.sessions.createIndex(

{ expireAt: 1 },

{ expireAfterSeconds: 0 }

)

// Analyze index usage

db.users.find({ email: "test@example.com" }).explain("executionStats")

Replication and Sharding

Replica Set Configuration

# Initialize replica set

rs.initiate({

_id: "myReplicaSet",

members: [

{ _id: 0, host: "mongo1:27017", priority: 2 },

{ _id: 1, host: "mongo2:27017", priority: 1 },

{ _id: 2, host: "mongo3:27017", priority: 1 }

]

})

# Check replica set status

rs.status()

# Read preference in application

const options = {

readPreference: 'secondaryPreferred',

readConcern: { level: 'majority' },

writeConcern: { w: 'majority', j: true }

}

Sharding for Scale

Horizontal scaling with sharding:

• Choose shard key carefully (high cardinality, even distribution)

• Enable sharding on database and collection

• Monitor chunk distribution and balancer activity

• Use hashed sharding for even distribution

• Consider zone sharding for geo-distribution

Best Practices

Schema Design

Design schemas based on query patterns. Denormalize for read performance when appropriate.

Index Management

Create indexes for frequent queries but avoid over-indexing. Monitor index usage and remove unused indexes.

Connection Pooling

Use connection pooling to reduce overhead. Set appropriate pool size based on application load.

Published on 2024-08-29 • Category: Database

← Back to Blog

NarvikHub

Free online developer tools and utilities for encoding, formatting, generating, and analyzing data. No registration required - all tools work directly in your browser.

Built for developers, by developers. Privacy-focused and open source.

Popular Tools

Base64 Encoder/DecoderJSON FormatterURL Encoder/DecoderHTML FormatterHash GeneratorUUID Generator

Blog Articles

Base64 Encoding GuideURL Encoding Deep DiveUnderstanding JWT TokensRegular Expressions GuideView All Articles →

Developer Tools & Utilities

Base64 Encoder/DecoderJSON FormatterURL Encoder/DecoderHTML FormatterHash GeneratorUUID GeneratorQR Code GeneratorJWT DecoderTimestamp ConverterRegex TesterText Diff CheckerHex ConverterImage Base64 ConverterASN.1 DecoderCharles Keygen

Free online tools for Base64 encoding, JSON formatting, URL encoding, hash generation, UUID creation, QR codes, JWT decoding, timestamp conversion, regex testing, and more.

Privacy PolicyTerms of ServiceContact

© 2024 NarvikHub. All rights reserved.