MongoDB(4)什么是集合(Collection)?

在MongoDB中,集合(Collection)是文档的容器,类似于关系型数据库中的表。一个数据库可以包含多个集合,每个集合包含多个文档。集合没有固定的模式(Schema),这意味着集合中的文档可以具有不同的结构和字段。

特点

  1. 无模式:集合中的文档不需要预定义结构,可以具有不同的字段和数据类型。
  2. 动态创建:集合在插入第一个文档时自动创建,无需显式创建。
  3. 灵活性:集合可以包含任何数据类型的文档,适用于灵活的数据模型。

示例

下面的示例展示了MongoDB集合的创建、插入文档、查询、更新和删除操作。

1. 创建和插入文档到集合

集合不需要显式创建,它会在插入第一个文档时自动创建。

javascript 复制代码
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

async function run() {
    try {
        await client.connect();
        console.log("Connected to MongoDB");

        const db = client.db('exampledb');
        const collection = db.collection('users'); // 创建或选择集合

        // 插入文档
        const insertResult = await collection.insertOne({
            name: "John Doe",
            email: "john.doe@example.com",
            age: 30
        });

        console.log('Inserted document:', insertResult.ops[0]);
    } finally {
        await client.close();
    }
}

run().catch(console.dir);
2. 查询集合中的文档

可以使用各种查询条件来检索集合中的文档。

javascript 复制代码
async function findDocuments() {
    try {
        await client.connect();
        const db = client.db('exampledb');
        const collection = db.collection('users');

        // 查询所有文档
        const allUsers = await collection.find().toArray();
        console.log('All users:', allUsers);

        // 按条件查询文档
        const user = await collection.findOne({ email: "john.doe@example.com" });
        console.log('Found user:', user);
    } finally {
        await client.close();
    }
}

findDocuments().catch(console.dir);
3. 更新集合中的文档

可以使用更新操作修改集合中的文档。

javascript 复制代码
async function updateDocument() {
    try {
        await client.connect();
        const db = client.db('exampledb');
        const collection = db.collection('users');

        // 更新文档
        const updateResult = await collection.updateOne(
            { email: "john.doe@example.com" },
            { $set: { age: 31 } }
        );

        console.log('Updated document count:', updateResult.modifiedCount);
    } finally {
        await client.close();
    }
}

updateDocument().catch(console.dir);
4. 删除集合中的文档

可以使用删除操作从集合中移除文档。

javascript 复制代码
async function deleteDocument() {
    try {
        await client.connect();
        const db = client.db('exampledb');
        const collection = db.collection('users');

        // 删除文档
        const deleteResult = await collection.deleteOne({ email: "john.doe@example.com" });
        console.log('Deleted document count:', deleteResult.deletedCount);
    } finally {
        await client.close();
    }
}

deleteDocument().catch(console.dir);

高级操作

索引

可以在集合中创建索引以提高查询性能。

javascript 复制代码
async function createIndex() {
    try {
        await client.connect();
        const db = client.db('exampledb');
        const collection = db.collection('users');

        // 创建索引
        const indexName = await collection.createIndex({ email: 1 });
        console.log('Created index:', indexName);
    } finally {
        await client.close();
    }
}

createIndex().catch(console.dir);
聚合操作

可以使用聚合管道对集合中的数据进行复杂的聚合操作。

javascript 复制代码
async function aggregateDocuments() {
    try {
        await client.connect();
        const db = client.db('exampledb');
        const collection = db.collection('orders');

        // 插入多个文档
        await collection.insertMany([
            { product: "Apple", quantity: 10, price: 2.5 },
            { product: "Banana", quantity: 5, price: 1.2 },
            { product: "Orange", quantity: 8, price: 3.0 }
        ]);

        // 使用聚合管道计算总销售额
        const aggregationPipeline = [
            { $group: { _id: null, total: { $sum: { $multiply: ["$quantity", "$price"] } } } }
        ];

        const aggResult = await collection.aggregate(aggregationPipeline).toArray();
        console.log('Total sales:', aggResult[0].total);
    } finally {
        await client.close();
    }
}

aggregateDocuments().catch(console.dir);

总结

MongoDB的集合提供了一个灵活且高效的方式来组织和管理文档数据。以下是其主要特点和常见操作:

特性 详细说明
无模式 集合中的文档可以具有不同的结构和字段
动态创建 集合在插入第一个文档时自动创建
灵活性 集合可以包含任何数据类型的文档
查询操作 丰富的查询条件和语法
更新操作 支持多种更新操作,如设置、增加、删除字段
删除操作 支持按条件删除文档
索引 支持多种索引类型,提高查询性能
聚合操作 支持复杂的数据聚合和处理

通过实际代码示例,可以直观地了解如何在MongoDB中使用集合进行数据存储和管理,从而更好地应用于实际项目开发中。

相关推荐
程序员小八7772 小时前
MySQL 事务:一文把 ACID、隔离级别、MVCC、锁全串起来
数据库·mysql
lzhdim2 小时前
提高 SQL 语句执行速度的方法
java·开发语言·数据库·sql·oracle
ltl3 小时前
ClickHouse Distributed 引擎与分布式查询路由
数据库
Wang's Blog3 小时前
PostgreSQL笔记60: 权限与角色管理——从层级体系到最佳实践
数据库·笔记·postgresql
whcyhhh4 小时前
头歌实践教学平台:大数据存储2023(六)
大数据·数据库·python
Elastic 中国社区官方博客5 小时前
让大模型思考,让小模型执行:在 Elastic Workflows 中拆分 LLM 成本
大数据·运维·数据库·人工智能·elasticsearch·ai
Faith_xzc5 小时前
一条 SQL 顶一条 Flink 链路?Doris Streaming Job 持续导入全景解析
大数据·数据库·sql·flink
这个DBA有点耶8 小时前
多模数据库深度解读:从“多库拼装”到“一库多能”的架构演进
数据库·mysql·dba
程序员夏洛8 小时前
MySQL 默认的事务隔离级别是什么?为什么选择这个级别?
数据库·mysql
艺术留白9 小时前
MokaTest使用篇-SQL接口
数据库·sql