CRUD(创建、读取、更新、删除)操作在 MongoDB 中使用 collections 上的 methods。它们处理文档并使用灵活的、类似 JSON 的查询语法——不同于 SQL,但在概念上是相似的。
Create — 插入文档
db..({ : , : });
db..([
{ : , : },
{ : , : }
]);
CRUD(创建、读取、更新、删除)操作在 MongoDB 中使用 collections 上的 methods。它们处理文档并使用灵活的、类似 JSON 的查询语法——不同于 SQL,但在概念上是相似的。
db..({ : , : });
db..([
{ : , : },
{ : , : }
]);
db.users.find(); // all documents
db.users.find({ age: 30 }); // WHERE age = 30 (a query filter object)
db.users.find({ age: { $gt: 25 } }); // age > 25 ($gt operator)
db.users.findOne({ name: "Ann" }); // the first match
db.users.find({ active: true }, { name: 1 }); // projection — return only the name field
查询使用过滤文档 ({ field: value }) 来描述要匹配的内容,使用 operators ($gt, $lt, $in 等) 来表示条件。Projection ({ name: 1 }) 选择要返回的字段。
// updateOne/updateMany with UPDATE OPERATORS ($set, $inc, etc.)
db.users.updateOne(
{ name: "Ann" }, // filter — which document
{ $set: { age: 31 } } // update — $set changes a field
);
db.users.updateMany(
{ active: false },
{ $set: { status: "inactive" } } // update all matching
);
db.users.updateOne({ name: "Ann" }, { $inc: { loginCount: 1 } }); // increment
更新采用过滤 (哪些文档) 和更新文档,使用operators 如 $set (设置字段)、$inc (增量)、$push (添加到数组) ——你不会替换整个文档 (除非有意)。
db.users.deleteOne({ name: "Ann" }); // delete the first match
db.users.deleteMany({ active: false }); // delete all matching
CRUD 操作是使用任何数据库的基础,因此理解它们在 MongoDB 中的工作原理是日常使用的基本知识。
这些操作——插入文档 (insertOne/insertMany)、使用过滤文档和 operators 进行查询 (find/findOne 使用 { field: value } 过滤器、比较 operators 如 $gt,以及投影来选择字段)、使用过滤器和更新 operators 进行更新 (updateOne/updateMany 使用 $set、$inc 等)、以及进行删除 (deleteOne/deleteMany) ——这些是应用程序在 MongoDB 中创建、读取、修改和删除数据的方式,是大多数数据库交互的核心。
理解 MongoDB 的独特方法很重要:查询使用过滤文档 (一个类似 JSON 的对象,描述要匹配的内容,并使用 operators),而不是 SQL 的 WHERE 语法,更新使用更新 operators ($set 来改变字段、$inc 来增量、$push 用于数组),而不是完全替换文档——这是一个不同但可学习的模型。
由于 CRUD 是任何数据驱动应用程序中的基本的、持续的操作,并且由于 MongoDB 的 CRUD methods、过滤文档查询和更新 operators 是你日常与数据库交互的方式,理解 MongoDB CRUD 操作——methods、过滤/operator 查询语法和更新 operators——是必不可少的、必知的知识,等同于了解 SQL 的 SELECT/INSERT/UPDATE/DELETE,以及使用数据库的实际基础。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠