0Pricing
MongoDB Academy · 课时

数据库、集合与命名空间

您将创建数据库、添加集合,并了解 MongoDB 如何在命名空间层级组织数据。

数据库、集合与命名空间 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MongoDB Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MongoDB Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

MongoDB's Three-Level Hierarchy

MongoDB nests data in three levels: Database, Collection, Document. It mirrors SQL's database, table, row — and one server can hold many of each.

What Is a Namespace?

A namespace names a collection by combining database and collection with a dot, like myapp.users. You'll see this notation in logs and explain output.

// Namespace: database.collection
// 'shop' database, 'products' collection:
use shop
db.products.find({})
// MongoDB internally refers to this as 'shop.products'

// You can also reference it explicitly:
db.getSiblingDB('shop').getCollection('products').find({})

Switching and Creating Databases

In mongosh, use switches databases. There's no CREATE DATABASE — MongoDB makes one lazily, the moment you insert your first document. The code shows it.

// Switch to (or create) a database
use myNewApp
// 'myNewApp' doesn't exist yet - no error, but not visible in 'show dbs'

// Insert a document to materialize the database
db.users.insertOne({ name: 'Alice' });

// Now 'myNewApp' appears:
show dbs
// admin     0.000GB
// local     0.000GB
// myNewApp  0.000GB

System Databases: admin, local, config

MongoDB keeps three system databases: admin for users and roles, local for replication data, and config for sharded-cluster metadata. Good to recognize, not to touch.

// View all databases on the server
show dbs
// admin   0.000GB
// config  0.000GB
// local   0.004GB
// shop    0.012GB
// myapp   0.008GB

// List databases programmatically
db.adminCommand({ listDatabases: 1 });

Creating Collections Explicitly

Use createCollection when you need special options up front — capped, time-series, clustered, or a schema validator. The code creates one with validation rules.

// Create a collection with a JSON Schema validator
db.createCollection('products', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['name', 'price'],
      properties: {
        name:  { bsonType: 'string' },
        price: { bsonType: 'number', minimum: 0 }
      }
    }
  }
});

Listing and Inspecting Collections

A few commands let you explore your database: list collections, get detailed info, and check storage stats. show collections is the quick one. The code shows more.

use shop

show collections
// orders
// products
// users

db.getCollectionInfos();
// Returns array of {name, type, options, idIndex} per collection

db.orders.stats().count;
// 15234

db.orders.totalIndexSize();
// 2359296 (bytes)

Renaming and Dropping Collections

You can rename a collection instantly, or drop one to delete it for good. Dropping is permanent — there's no recycle bin, so back up first in production.

// Rename a collection
db.oldUsers.renameCollection('users');
// { ok: 1 }

// Drop a collection - IRREVERSIBLE
db.tempData.drop();
// true

// Drop the entire database - EXTREMELY DANGEROUS
// db.dropDatabase();
// Use only in development or with full backup

Multi-Tenancy With Databases

For SaaS apps, multi-tenancy can mean a database per customer for strong isolation, or one shared collection filtered by a tenantId field. The code shows both.

// Option 1: Database-per-tenant
const db = client.db('tenant_' + tenantId);
db.users.find({});
// Each tenant has completely isolated data

// Option 2: Shared collection with tenantId field
const db = client.db('saas_app');
db.users.find({ tenantId: tenantId });
// All tenants share one collection, filtered by tenantId

Collection Naming Best Practices

A few naming habits prevent headaches: stay consistent, use plural nouns like users, and avoid special characters. Good naming conventions make code easier to read.

// Good collection names
db.users.find({});
db.order_items.find({});
db.productCategories.find({});

// Avoid these
db['$sales'].find({});        // $ prefix causes issues
db['system.logs'].find({});   // reserved prefix
db['my.collection'].find({}); // dot in name causes confusion

The WiredTiger Storage Engine

MongoDB's default storage engine is WiredTiger. It allows many writes at once without blocking, compresses data on disk, and journals writes so crashes don't lose data.

// Check current storage engine
db.serverStatus().storageEngine;
// { name: 'wiredTiger', supportsCommittedReads: true, ... }

// Collection stats show compression savings
db.orders.stats();
// storageSize: 2097152 (compressed on disk)
// size: 8388608 (uncompressed logical size)

Understanding the Oplog

The oplog is a special log of every write in a replica set. Secondaries replay it to stay in sync, and it also powers MongoDB's live Change Streams.

// Inspect oplog in mongosh (replica set members only)
use local
db.oplog.rs.find().sort({ $natural: -1 }).limit(3);
// { op: 'i', ns: 'shop.orders', o: { _id: ..., ... } }
// op: 'i'=insert, 'u'=update, 'd'=delete, 'c'=command

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

You learned MongoDB organizes data as Database, Collection, Document, that databases are created lazily, and that WiredTiger powers storage. Next: the mongosh shell.

常见问题解答

「数据库、集合与命名空间」课时是免费的吗?

是的 — 「数据库、集合与命名空间」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。

「数据库、集合与命名空间」这节课中我会学到什么?

您将创建数据库、添加集合,并了解 MongoDB 如何在命名空间层级组织数据。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 MongoDB Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「数据库、集合与命名空间」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 MongoDB Academy 课中编写并运行代码吗?

能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 什么是 BSON 文档
  2. 集合与 SQL 表的比较
  3. 数据库、集合与命名空间
  4. mongosh Shell 基础
← 返回 MongoDB Academy