Skip to content

MongoDB 基础

工作使用 MongoDB: 集合, documents, CRUD 操作, and querying.

你将学到

  • 如何 MongoDB 存储数据 as BSON documents in 集合
  • Inserting documents 使用 insertOne and insertMany
  • Querying 使用查找, 筛选, and projection
  • 更新 documents 使用 updateOne and 运算符
  • Indexing and _id 字段

概念讲解

文档和集合

MongoDB stores data as documents (JSON-like objects encoded as BSON) grouped into collections. A collection is analogous to a table, and a document is analogous to a row — but documents are flexible: each document in a collection can have a different shape. Every document automatically gets an _id field (a 12-byte ObjectId by default) that serves as the primary key.

Inserting Documents

insertOne adds a single document; insertMany adds multiple. You provide the document as a JavaScript object. Fields can be strings, numbers, booleans, arrays, nested objects, dates, and more. If you do not specify _id, MongoDB generates one automatically.

Querying with find

db.集合.查找(查询, projection) returns matching documents. The query is an object specifying filter conditions: { 状态: 'active' }, { price: { $gt: 50 } }, { 标签: 'red' } (matches if 'red' is in the array). Operators like $gt, $lt, $in, $regex, and $and build complex filters. The projection specifies which fields to include or exclude.

Updating Documents

updateOne and updateMany modify documents. Use update operators: $设置 (set a field), $inc (increment), $推送 (append to array), $拉取 (remove from array), $unset (remove a field). replaceOne replaces the entire document. Use upsert: 真 to insert if no match exists.

Indexing

MongoDB supports indexes on any field, including nested fields and array elements. db.集合.createIndex({ 字段: 1 }) creates an ascending index. Without an index, MongoDB scans every document in the collection (a "集合 scan"). Indexes are essential for performance on large collections. Use db.集合.查找(...).解释() to check if an index is used.

示例代码

              -- Insert a document
db.products.insertOne({
  name: "Wireless Keyboard",
  price: 49.99,
  category: "electronics",
  tags: ["wireless", "usb", "keyboard"],
  specs: { batteryLife: "12 months", layout: "QWERTY" },
  inStock: true
});

-- Query with filter and projection
db.products.find(
  { price: { $gt: 20 }, category: "electronics" },
  { name: 1, price: 1, _id: 0 }
).sort({ price: -1 }).limit(10);

-- Update with operators
db.products.updateOne(
  { name: "Wireless Keyboard" },
  { $set: { price: 39.99 }, $push: { tags: "sale" } }
);

-- Create an index on the price field
db.products.createIndex({ price: 1 });
db.products.createIndex({ category: 1, price: -1 });
            

Four MongoDB 操作: insert document 使用 nested 数据, 查询使用筛选 and projection, 更新使用 $设置 and $推送, and 创建单个 and compound 索引.

动手试一试

  • JSON Formatter

    格式 MongoDB documents and 查询 results as JSON.

  • JSON Path

    查询 nested document 字段使用 JSONPath 表达式.

常见错误

错误写法

不创建索引 on 频繁地 queried 字段

正确做法

不使用索引, MongoDB scans 每个 document. 创建索引 on 字段 used in 查找筛选, 排序, and 连接 ($lookup). Use 解释() 到验证.

错误写法

Using MongoDB for highly relational 数据使用许多连接

正确做法

MongoDB's $lookup 连接是 有限 and 慢 compared 到 SQL 连接. 如果你的数据是 highly relational 使用许多连接, relational 数据库是 likely better fit.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误