How to perform document operations

MongoDBMongoDBBeginner
Practice Now

Introduction

This tutorial provides a comprehensive guide to performing document operations in MongoDB, covering essential techniques for managing and manipulating data in a NoSQL database environment. Developers will learn how to effectively create, read, update, and delete documents, as well as perform advanced querying and aggregation operations.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/AggregationOperationsGroup(["`Aggregation Operations`"]) mongodb/BasicOperationsGroup -.-> mongodb/start_mongodb_shell("`Start MongoDB Shell`") mongodb/BasicOperationsGroup -.-> mongodb/create_database_collection("`Create Database and Collection`") mongodb/BasicOperationsGroup -.-> mongodb/insert_document("`Insert Document`") mongodb/BasicOperationsGroup -.-> mongodb/update_document("`Update Document`") mongodb/BasicOperationsGroup -.-> mongodb/delete_document("`Delete Document`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/AggregationOperationsGroup -.-> mongodb/group_documents("`Group Documents`") mongodb/AggregationOperationsGroup -.-> mongodb/aggregate_group_totals("`Aggregate Group Totals`") subgraph Lab Skills mongodb/start_mongodb_shell -.-> lab-435543{{"`How to perform document operations`"}} mongodb/create_database_collection -.-> lab-435543{{"`How to perform document operations`"}} mongodb/insert_document -.-> lab-435543{{"`How to perform document operations`"}} mongodb/update_document -.-> lab-435543{{"`How to perform document operations`"}} mongodb/delete_document -.-> lab-435543{{"`How to perform document operations`"}} mongodb/find_documents -.-> lab-435543{{"`How to perform document operations`"}} mongodb/query_with_conditions -.-> lab-435543{{"`How to perform document operations`"}} mongodb/group_documents -.-> lab-435543{{"`How to perform document operations`"}} mongodb/aggregate_group_totals -.-> lab-435543{{"`How to perform document operations`"}} end

MongoDB Document Basics

What is a MongoDB Document?

A MongoDB document is a data structure composed of field-value pairs, similar to JSON objects. It is the basic unit of data storage in MongoDB, offering a flexible and dynamic schema approach.

Document Structure

graph LR A[Document] --> B[Field 1] A --> C[Field 2] A --> D[Field 3] B --> E[Key: Value] C --> F[Key: Value] D --> G[Key: Value]

Key Characteristics

  • Stored in BSON (Binary JSON) format
  • Maximum document size is 16MB
  • Supports nested documents and arrays

Document Example

## Example MongoDB document
{
    "_id": ObjectId("5f8d7a3b1c9d440000f5e123"),
    "username": "labexuser",
    "age": 28,
    "skills": ["Python", "MongoDB", "Linux"],
    "address": {
        "city": "Beijing",
        "country": "China"
    }
}

Document Field Types

Type Description Example
String Text data "Hello World"
Integer Whole numbers 42
Double Floating-point numbers 3.14
Boolean True/False values true
Array Ordered collection ["apple", "banana"]
Object Embedded document {"key": "value"}
ObjectId Unique document identifier ObjectId(...)
Timestamp Date and time new Date()

Document Naming Conventions

  • Field names are case-sensitive
  • Cannot start with $
  • Cannot contain .
  • Recommended to use camelCase or snake_case

Creating Documents in MongoDB

## Insert a single document
db.users.insertOne({
    "username": "labexuser",
    "email": "[email protected]",
    "age": 25
})

## Insert multiple documents
db.users.insertMany([
    {"username": "john", "age": 30},
    {"username": "jane", "age": 28}
])

Best Practices

  1. Keep documents relatively small
  2. Use meaningful field names
  3. Avoid deeply nested structures
  4. Leverage MongoDB's flexible schema

Performance Considerations

  • Indexes improve query performance
  • Limit document size
  • Use appropriate data types
  • Avoid excessive document nesting

By understanding these MongoDB document basics, you'll be well-prepared to work with NoSQL database operations in LabEx learning environments.

CRUD Document Operations

Overview of CRUD Operations

graph TD A[CRUD Operations] --> B[Create] A --> C[Read] A --> D[Update] A --> E[Delete]

Create Operations

insertOne()

## Insert a single document
db.users.insertOne({
    username: "labexuser",
    email: "[email protected]",
    age: 25
})

insertMany()

## Insert multiple documents
db.users.insertMany([
    { username: "john", age: 30 },
    { username: "jane", age: 28 }
])

Read Operations

find() Method

## Retrieve all documents
db.users.find()

## Find documents with specific conditions
db.users.find({ age: { $gt: 25 } })

Query Operators

Operator Description Example
$eq Equal to { field: { $eq: value } }
$gt Greater than { field: { $gt: value } }
$lt Less than { field: { $lt: value } }
$in Match any value in array { field: { $in: [value1, value2] } }

Update Operations

updateOne()

## Update a single document
db.users.updateOne(
    { username: "labexuser" },
    { $set: { age: 26 } }
)

updateMany()

## Update multiple documents
db.users.updateMany(
    { age: { $lt: 30 } },
    { $inc: { age: 1 } }
)

Update Operators

Operator Description Example
$set Set field value { $set: { field: value } }
$inc Increment value { $inc: { field: number } }
$push Add element to array { $push: { array: value } }
$pull Remove element from array { $pull: { array: value } }

Delete Operations

deleteOne()

## Delete a single document
db.users.deleteOne({ username: "john" })

deleteMany()

## Delete multiple documents
db.users.deleteMany({ age: { $lt: 25 } })

Advanced Query Techniques

Projection

## Select specific fields
db.users.find(
    { age: { $gt: 25 } },
    { username: 1, email: 1, _id: 0 }
)

Sorting and Limiting

## Sort and limit results
db.users.find()
    .sort({ age: 1 })
    .limit(5)

Best Practices

  1. Use appropriate indexes
  2. Minimize the number of operations
  3. Validate input data
  4. Handle errors gracefully

Performance Considerations

  • Avoid large, complex queries
  • Use projection to reduce data transfer
  • Leverage indexing
  • Monitor query performance

By mastering these CRUD operations in LabEx MongoDB environments, you'll efficiently manage document data with precision and ease.

Query and Aggregation

Query Fundamentals

graph LR A[MongoDB Queries] --> B[Simple Queries] A --> C[Complex Queries] A --> D[Aggregation Pipeline]

Advanced Query Techniques

Comparison Operators

## Find users older than 25
db.users.find({ age: { $gt: 25 } })

## Find users between 20 and 30
db.users.find({
    age: {
        $gte: 20,
        $lte: 30
    }
})

Logical Operators

## AND condition
db.users.find({
    $and: [
        { age: { $gt: 25 } },
        { city: "Beijing" }
    ]
})

## OR condition
db.users.find({
    $or: [
        { age: { $lt: 20 } },
        { status: "active" }
    ]
})

Aggregation Framework

Aggregation Pipeline Stages

Stage Description Example
$match Filter documents { $match: { age: { $gt: 25 } } }
$group Group by field { group: { _id: "department", total: { $sum: 1 } } }
$sort Sort results { $sort: { age: -1 } }
$limit Limit results { $limit: 5 }
$project Select fields { $project: { name: 1, age: 1 } }

Complex Aggregation Example

db.sales.aggregate([
    ## Match sales over $1000
    { $match: { amount: { $gt: 1000 } } },

    ## Group by product and calculate total sales
    { $group: {
        _id: "$product",
        totalSales: { $sum: "$amount" },
        averagePrice: { $avg: "$amount" }
    }},

    ## Sort by total sales descending
    { $sort: { totalSales: -1 } },

    ## Limit to top 5 products
    { $limit: 5 }
])
## Create text index
db.articles.createIndex({ content: "text" })

## Perform text search
db.articles.find({
    $text: { $search: "mongodb tutorial" }
})

Geospatial Queries

## Create geospatial index
db.locations.createIndex({ location: "2dsphere" })

## Find nearby locations
db.locations.find({
    location: {
        $near: {
            $geometry: {
                type: "Point",
                coordinates: [-73.9667, 40.78]
            },
            $maxDistance: 1000
        }
    }
})

Aggregation Pipeline Visualization

graph LR A[Input Documents] --> B[$match] B --> C[$group] C --> D[$sort] D --> E[$limit] E --> F[Output Results]

Performance Optimization

  1. Use indexes strategically
  2. Minimize data processing stages
  3. Use $match early in pipeline
  4. Limit result sets
  5. Avoid complex nested aggregations

Advanced Query Patterns

Lookup (Join-like Operation)

db.orders.aggregate([
    { $lookup: {
        from: "users",
        localField: "user_id",
        foreignField: "_id",
        as: "user_details"
    }}
])

Best Practices in LabEx MongoDB Environments

  • Profile and analyze query performance
  • Use explain() to understand query execution
  • Choose appropriate indexing strategies
  • Leverage aggregation for complex data transformations

By mastering these query and aggregation techniques, you'll unlock powerful data manipulation capabilities in MongoDB, making your data analysis more efficient and insightful.

Summary

By mastering MongoDB document operations, developers can efficiently manage complex data structures, perform sophisticated queries, and leverage the powerful features of this flexible NoSQL database. The tutorial equips learners with practical skills to handle document-based data operations with confidence and precision.

Other MongoDB Tutorials you may like