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中使用集合进行数据存储和管理,从而更好地应用于实际项目开发中。

相关推荐
TDengine (老段)7 分钟前
TDengine 索引使用指南 — 何时建、怎么建、怎么用
java·大数据·数据库·物联网·时序数据库·tdengine·涛思数据
ATA888816 分钟前
企业数据库账号安全的技术解决方案
数据库·安全
DB哥讲数据库16 分钟前
MySQL 8.4 安装教程:超详细图文讲解(附mysql安装包)
linux·数据库·mysql·centos
Databend19 分钟前
AST Visitor API 迁移,怎么证明 AI 没改坏 SQL 语义?
数据库·ai编程
TDengine (老段)23 分钟前
TDengine DDL 完整参考 — Database/STable/Table/Column/Tag
大数据·数据库·物联网·时序数据库·tdengine·涛思数据
xlxxy_24 分钟前
sap获取批次特性报表
java·linux·开发语言·前端·数据库·abap·mm
栋***t35 分钟前
从“工具”到“基建”,麦塔在线考试系统经历的时代变局与定位逻辑
java·大数据·数据库·开源软件·无纸化
SelectDB技术团队42 分钟前
Agent 可观测性:Apache Doris / SelectDB 的技术能力、选型对比与实践
数据库·人工智能·agent·可观测·ai-native·apache doris·selectdb
csdn2015_1 小时前
kafka如何确保消息不丢失
数据库·分布式·kafka
wefg11 小时前
【MySQL】MySQL C API 访问 MySQL
数据库·mysql