paint-brush
MongoDB - A Practical Guide for Beginners and Experts Alikeby@renanb
304 reads
304 reads

MongoDB - A Practical Guide for Beginners and Experts Alike

by Renan BotasseJanuary 29th, 2025
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

This text is a practical guide to performing basic operations in MongoDB. It focuses on essential topics like CRUD operations (Create, Read, Update, Delete) and customising queries with sorting, pagination and projections.
featured image - MongoDB - A Practical Guide for Beginners and Experts Alike
Renan Botasse HackerNoon profile picture

This text is a practical guide to performing basic operations in MongoDB, one of the most popular NoSQL databases for storing and managing data. It focuses on essential topics like CRUD operations (Create, Read, Update, Delete), customizing queries with sorting, pagination, and projections, and more advanced techniques such as the Aggregation Framework.


In addition to these, this guide touches on:

Using query operators for filtering data (e.g., $eq, $gt, $in), working with nested fields, utilizing logical operators ($and, $or, $not), managing arrays with operators like $push and $unwind, and even performing joins between collections with $lookup. Whether you’re a beginner looking to get started or an experienced user aiming to brush up on key concepts, this guide provides a clear and concise overview of MongoDB's most practical and widely used features.


1. CRUD Operations (Create, Read, Update, Delete)

1.1 Create - Inserting Data

  • insertOne(): Insert a single document.

    db.collection.insertOne({ name: "John", age: 25 });
    
  • insertMany(): Insert multiple documents.

    db.collection.insertMany([{ name: "Maria" }, { name: "Peter" }]);
    

1.2 Read - Querying Data

  • find(): Retrieve multiple documents.

    db.collection.find({ age: { $gte: 18 } });
    
  • findOne(): Retrieve a single document.

    db.collection.findOne({ name: "John" });
    

Query Operators

  • $eq: Equal to.
  • $ne: Not equal to.
  • $gt, $lt, $gte, $lte: Numeric comparisons.
  • $in, $nin: Check if a value is inside/outside a list.
  • $exists: Check if a field exists.

1.3 Update - Updating Data

  • updateOne(): Update a single document.

    db.collection.updateOne({ name: "John" }, { $set: { age: 30 } });
    
  • updateMany(): Update multiple documents.

    db.collection.updateMany({ age: { $lt: 18 } }, { $inc: { age: 1 } });
    

Update Operators

  • $set: Modify fields.
  • $inc: Increment numeric values.
  • $push, $pull: Add/remove elements from arrays.

1.4 Delete - Deleting Data

  • deleteOne(): Delete a single document.

    db.collection.deleteOne({ name: "Peter" });
    
  • deleteMany(): Delete multiple documents.

    db.collection.deleteMany({ age: { $lt: 18 } });
    

2. Customizing Queries

2.1 Field Projection

  • Return specific fields:

    db.collection.find({}, { name: 1, _id: 0 });
    

2.2 Sorting and Pagination

  • Sorting:

    db.collection.find().sort({ age: 1 });
    
  • Pagination:

    db.collection.find().skip(5).limit(10);
    

2.3 Regular Expressions

  • Partial search:

    db.collection.find({ name: /john/i });
    

2.4 Querying Nested Fields

  • Query within subfields:

    db.collection.find({ "address.city": "New York" });
    

2.5 Logical Operators

  • $and:

    db.collection.find({ $and: [{ age: { $gte: 18 } }, { city: "Los Angeles" }] });
    
  • $or:

    db.collection.find({ $or: [{ city: "New York" }, { city: "San Francisco" }] });
    

3. Aggregation Framework

3.1 Aggregation Pipeline

  • A sequence of stages to transform data:

    db.collection.aggregate([
      { $match: { age: { $gte: 18 } } },
      { $group: { _id: "$city", total: { $sum: 1 } } }
    ]);
    

3.2 Key Stages

3.2.1 $match (Filtering Data)

  • Filter documents in the pipeline:

    { $match: { age: { $gte: 18 } } }
    

3.2.2 $project (Data Transformation)

  • Create or modify fields:

    { $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] } } }
    

3.2.3 $group (Data Grouping)

  • Group by a field and perform calculations:

    { $group: { _id: "$city", total: { $sum: 1 } } }
    

3.2.4 Sorting and Limiting

  • Sorting:

    { $sort: { total: -1 } }
    
  • Limiting:

    { $limit: 10 }
    

3.2.5 Array Manipulation

  • $unwind: Expand arrays into individual documents:

    { $unwind: "$hobbies" }
    

3.2.6 $lookup (Relationships)

  • Perform "joins" between collections:

    {
      $lookup: {
        from: "orders",
        localField: "userId",
        foreignField: "userId",
        as: "userOrders"
      }
    }
    

3.2.7 $out (Export Results)

  • Export results to a new collection:

    { $out: "newCollection" }