📚 Working with MongoDB
📚 使用 MongoDB
🗂️ Schema Design
🗂️ 模式设计
- Schemas provide a blueprint for data organization and storage.
- 模式为数据组织和存储提供了蓝图。
- MongoDB is schema-less but using schemas can enhance:
- MongoDB 是无模式的,但使用模式可以增强:
- Consistency and Data Integrity: Ensures uniformity across documents in a collection.
- 一致性和数据完整性:确保集合中文档的一致性。
- Improved Query Performance: Optimizes queries by defining expected document structures, allowing efficient indexing.
- 改进的查询性能:通过定义预期的文档结构来优化查询,从而实现高效索引。
- Enhanced Developer Productivity: Predefined structures help developers write error-free queries more easily.
- 提高开发者生产力:预定义的结构帮助开发者更轻松地编写无错误的查询。
- Simplified Maintenance: Clear data structure facilitates updates and changes.
- 简化维护:清晰的数据结构有助于更新和更改。
- Better Collaboration: Shared schema fosters teamwork and reduces miscommunication.
- 更好的协作:共享模式促进团队合作并减少沟通不畅。
Schema: A logical structure defining the organization of data within a database.
模式:定义数据库中数据组织的逻辑结构。
💡 Benefits of Using Schemas
💡 使用模式的好处
- Consistency: Prevents inconsistent data storage (e.g., missing fields in an eCommerce application).
- 一致性:防止数据存储不一致(例如,电子商务应用程序中缺少字段)。
- Performance: Optimized indexing and query execution for large datasets.
- 性能:针对大型数据集优化索引和查询执行。
- Productivity: Tools support schema-defined data, aiding development.
- 生产力:工具支持模式定义的数据,辅助开发。
🌐 Data Modeling in MongoDB
🌐 MongoDB 中的数据建模
- Data modeling differs significantly from relational databases, balancing user interaction demands and performance needs.
- 数据建模与关系数据库显着不同,需要在用户交互需求和性能需求之间取得平衡。
- Document Structure: MongoDB uses flexible documents that can manage nested BSON documents and arrays.
- 文档结构:MongoDB 使用灵活的文档,可以管理嵌套的 BSON 文档和数组。
📝 Benefits of Document Structure
📝 文档结构的好处
- Reduced Need for Joins: Related data can be kept together in one document, simplifying retrieval.
- 减少连接需求:相关数据可以保存在一个文档中,简化检索。
- Streamlined Data Retrieval: All related information can be fetched in a single query.
- 简化数据检索:所有相关信息都可以通过单个查询获取。
- Simplified Queries: Queries become less complex, reducing errors.
- 简化查询:查询变得不那么复杂,减少错误。
Example Document:
示例文档:
1 | { |
🔍 Data Types in MongoDB
🔍 MongoDB 中的数据类型
- BSON (Binary JSON): The format MongoDB uses to store data, extending JSON to support additional types like dates and binary data.
- BSON (二进制 JSON):MongoDB 用于存储数据的格式,扩展了 JSON 以支持日期和二进制数据等其他类型。
Understanding these concepts and practices in MongoDB will significantly improve database management efficiency and application performance.
理解 MongoDB 中的这些概念和实践将显着提高数据库管理效率和应用程序性能。
📊 MongoDB Data Types
📊 MongoDB 数据类型
Basic Data Types
基本数据类型
- String
- 字符串
- Description: UTF-8 encoded textual data.
- 描述:UTF-8 编码的文本数据。
- Example:
{ "name": "John Doe" } - 示例:
{ "name": "John Doe" } - Use Case: Names, addresses, descriptions.
- 用例:姓名、地址、描述。
- Integer
- 整数
- Description: 32-bit and 64-bit integers for numerical data.
- 描述:用于数值数据的 32 位和 64 位整数。
- Example:
{ "age": 30, "score": 123456789 } - 示例:
{ "age": 30, "score": 123456789 } - Use Case: Counting items, storing IDs.
- 用例:计数项目、存储 ID。
- Double
- 双精度浮点数
- Description: Floating-point numbers with decimal points.
- 描述:带小数点的浮点数。
- Example:
{ "price": 19.99, "rating": 4.5 } - 示例:
{ "price": 19.99, "rating": 4.5 } - Use Case: Prices, ratings.
- 用例:价格、评分。
- Boolean
- 布尔值
- Description: Represents binary values: true or false.
- 描述:表示二进制值:true 或 false。
- Example:
{ "isActive": true, "isAdmin": false } - 示例:
{ "isActive": true, "isAdmin": false } - Use Case: Flags and toggles.
- 用例:标志和开关。
Complex Data Types
复杂数据类型
Arrays
数组
- Description: Stores multiple values in a single field.
- 描述:在单个字段中存储多个值。
- Example:
{ "tags": ["mongodb", "database", "NoSQL"] } - 示例:
{ "tags": ["mongodb", "database", "NoSQL"] } - Use Case: Lists, categories.
- 用例:列表、类别。
Embedded Documents
嵌入式文档
Description: Documents nested within other documents.
描述:嵌套在其他文档中的文档。
Example:
示例:
1
2
3
4
5
6
7
8
9{
"name": "John Doe",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}Use Case: Complex structures like addresses.
用例:复杂结构,如地址。
Special Data Types
特殊数据类型
- ObjectId
- ObjectId
- Description: Unique identifier for documents.
- 描述:文档的唯一标识符。
- Example:
{ "_id": ObjectId("507f1f77bcf86cd799439011") } - 示例:
{ "_id": ObjectId("507f1f77bcf86cd799439011") } - Use Case: Unique document identification.
- 用例:唯一文档标识。
- Date
- 日期
- Description: Stores current date/time as milliseconds since Unix epoch.
- 描述:以自 Unix 纪元以来的毫秒数存储当前日期/时间。
- Example:
{ "created_at": ISODate("2023-07-24T00:00:00Z") } - 示例:
{ "created_at": ISODate("2023-07-24T00:00:00Z") } - Use Case: Timestamps, event tracking.
- 用例:时间戳、事件跟踪。
- Null
- Null
- Description: Represents the absence of a value.
- 描述:表示缺少值。
- Example:
{ "middle_name": null } - 示例:
{ "middle_name": null } - Use Case: Optional fields.
- 用例:可选字段。
- Regular Expression
- 正则表达式
- Description: Pattern matching within strings.
- 描述:字符串内的模式匹配。
- Example:
{ "pattern": /abc/i } - 示例:
{ "pattern": /abc/i } - Use Case: Search and validation.
- 用例:搜索和验证。
- Binary Data
- 二进制数据
- Description: Stores binary content like images.
- 描述:存储图像等二进制内容。
- Example:
{ "profile_picture": BinData(0, "base64encodedstring") } - 示例:
{ "profile_picture": BinData(0, "base64encodedstring") } - Use Case: Multimedia content storage.
- 用例:多媒体内容存储。
🗂️ Understanding Relationships in MongoDB
🗂️ 理解 MongoDB 中的关系
One-to-One Relationships
一对一关系
- Description: A single document in one collection relates to a single document in another.
- 描述:一个集合中的单个文档与另一个集合中的单个文档相关联。
- Example: User and Profile.
- 示例:用户和个人资料。
- Implementation Options:
- 实现选项:
- Embedding: Store profile within the user document.
- 嵌入:将个人资料存储在用户文档中。
- Referencing: Store profile in a separate collection and reference it.
- 引用:将个人资料存储在单独的集合中并引用它。
One-to-Many Relationships
一对多关系
- Description: A single document relates to multiple documents.
- 描述:单个文档与多个文档相关联。
- Example: Author and Posts.
- 示例:作者和帖子。
- Implementation Options:
- 实现选项:
- Embedding: Store an array of posts within the author document.
- 嵌入:在作者文档中存储帖子数组。
- Referencing: Store posts in a separate collection with references to authors.
- 引用:将帖子存储在单独的集合中,并引用作者。
Many-to-Many Relationships
多对多关系
- Description: Multiple documents in one collection relate to multiple documents in another.
- 描述:一个集合中的多个文档与另一个集合中的多个文档相关联。
- Example: Students and Courses.
- 示例:学生和课程。
- Implementation Options:
- 实现选项:
- Embedding Arrays: Embed ObjectIds in both student and course documents.
- 嵌入数组:在学生和课程文档中都嵌入 ObjectId。
📊 MongoDB Relationships
📊 MongoDB 关系
Types of Relationships:
关系类型:
- One-to-One: Use embedding for small, frequently accessed related data.
- 一对一:对于小型、频繁访问的相关数据使用嵌入。
- One-to-Many: Use embedding for limited related documents, referencing for larger documents.
- 一对多:对于有限的相关文档使用嵌入,对于较大的文档使用引用。
- Many-to-Many:
- 多对多:
- Embedding Arrays: Suitable for small, manageable relationships.
- 嵌入数组:适用于小型、易于管理的关系。
- Join Collection: Preferred for large, complex relationships.
- 连接集合:大型、复杂关系的首选。
Understanding relationships is crucial for efficient database design and management.
理解关系对于高效的数据库设计和管理至关重要。
💡 CRUD Operations Overview
💡 CRUD 操作概述
CRUD Definition:
CRUD 定义:
CRUD stands for Create, Read, Update, and Delete—the four basic operations on data.
CRUD 代表创建、读取、更新和删除——对数据的四种基本操作。
Inserting Documents:
插入文档:
Single Document: Use
insertOnemethod.单个文档:使用
insertOne方法。- Example:
db.movies.insertOne({"title" : "Stand by Me"}) - 示例:
db.movies.insertOne({"title" : "Stand by Me"})
- Example:
Multiple Documents: Use
insertMany.多个文档:使用
insertMany。- Example:
- 示例:
1
2
3
4
5db.movies.insertMany([
{"title" : "Ghostbusters"},
{"title" : "E.T."},
{"title" : "Blade Runner"}
]);
Removing Documents:
删除文档:
- Delete One:
deleteOneremoves a single document matching the filter. - 删除单个:
deleteOne删除与筛选器匹配的单个文档。- Example:
db.movies.deleteOne({"_id" : 4}) - 示例:
db.movies.deleteOne({"_id" : 4})
- Example:
- Delete Many:
deleteManyremoves all documents matching the filter. - 删除多个:
deleteMany删除与筛选器匹配的所有文档。- Example:
db.movies.deleteMany({"year" : 1984}) - 示例:
db.movies.deleteMany({"year" : 1984})
- Example:
- Dropping a Collection: Use
db.movies.drop()to remove the entire collection. - 删除集合:使用
db.movies.drop()删除整个集合。
🔄 Updating Documents
🔄 更新文档
Update Methods:
更新方法:
- updateOne: Updates a single document.
- updateOne:更新单个文档。
- updateMany: Updates multiple documents.
- updateMany:更新多个文档。
- replaceOne: Replaces a document entirely.
- replaceOne:完全替换一个文档。
Document updates are atomic; the last update sent will prevail in case of conflicts.
文档更新是原子性的;如果发生冲突,最后发送的更新将生效。
Example of Document Replacement:
文档替换示例:
Changing user document structure:
更改用户文档结构:
1
2
3
4
5var joe = db.users.findOne({"name" : "joe"});
joe.relationships = {"friends" : joe.friends, "enemies" : joe.enemies};
delete joe.friends;
delete joe.enemies;
db.users.replaceOne({"name" : "joe"}, joe);
📈 Best Practices for MongoDB Relationships
📈 MongoDB 关系的最佳实践
| Relationship Type关系类型 | Recommended Approach推荐方法 |
|---|---|
| One-to-One | Embedding for small, frequently accessed data |
| 一对一 | 对于小型、频繁访问的数据使用嵌入 |
| One-to-Many | Embedding for limited documents, referencing for larger data |
| 一对多 | 对于有限的文档使用嵌入,对于较大的数据使用引用 |
| Many-to-Many | Embedding for small relationships, join collection for complex relationships |
| 多对多 | 对于小型关系使用嵌入,对于复杂关系使用连接集合 |
🗃️ Working with MongoDB
🗃️ 使用 MongoDB
🔑 Key Concepts
🔑 核心概念
- Unique Document Identification:
- 唯一文档标识:
- Each document in a MongoDB collection has a unique
_idfield. - MongoDB 集合中的每个文档都有一个唯一的
_id字段。 - When updating a document, ensure you match on a unique identifier to avoid conflicts.
- 更新文档时,请确保通过唯一标识符进行匹配以避免冲突。
- Each document in a MongoDB collection has a unique
Example: To update Joe’s age, instead of matching by name, match by _id:
示例:要更新 Joe 的年龄,应通过 _id 而不是姓名进行匹配:
1 db.people.replaceOne({"_id" : ObjectId("4b2b9f67a1f631733d917a7c")}, joe);
📝 Updating Documents
📝 更新文档
Incrementing Values: Use the
++operator to increment numeric fields.递增值:使用
1
++
运算符来递增数字字段。
- Example: Increment Joe’s age:
- 示例:增加 Joe 的年龄:
1
joe.age++;
📊 Array Operators
📊 数组操作符
Adding Elements:
添加元素:
$push: Adds an element to the end of an array.$push:将元素添加到数组的末尾。- Example: Adding a comment to a blog post:
- 示例:向博客文章添加评论:
1
db.blog.posts.updateOne({"title" : "A blog post"}, {"$push" : {"comments" : {"name" : "joe", "content" : "nice post."}}});
Multiple Additions:
多重添加:
$each: Push multiple values at once.$each:一次推送多个值。- Example:
- 示例:
1
db.stock.ticker.updateOne({"_id" : "GOOG"}, {"$push" : {"hourly" : {"$each" : [562.776, 562.790, 559.123]}}});
Limiting Array Size:
限制数组大小:
$slice: Limits the array size.$slice:限制数组大小。- Example: Keep only the last 10 elements:
- 示例:仅保留最后 10 个元素:
1
db.movies.updateOne({"genre" : "horror"}, {"$push" : {"top10" : {"$each" : ["Nightmare on Elm Street", "Saw"], "$slice" : -10}}});
Preventing Duplicates:
防止重复:
$addToSet: Adds a value only if it doesn’t already exist in the array.$addToSet:仅当值不存在于数组中时才添加该值。- Example:
- 示例:
1
db.users.updateOne({"_id" : ObjectId("4b2d75476cc613d5ee930164")}, {"$addToSet" : {"emails" : "joe@gmail.com"}});
🚫 Removing Elements
🚫 删除元素
Removing by Position:
按位置删除:
$pop: Removes an element from the beginning or end of an array.$pop:从数组的开头或末尾删除元素。- Example: Remove from the end:
- 示例:从末尾删除:
1
db.lists.updateOne({}, {"$pop" : {"todo" : 1}});
Removing by Criteria:
按条件删除:
$pull: Removes elements that match specified criteria.$pull:删除符合指定条件的元素。- Example: Remove “laundry” from a todo list:
- 示例:从待办事项列表中删除 “laundry”:
1
db.lists.updateOne({}, {"$pull" : {"todo" : "laundry"}});
🔄 Positional Array Modification
🔄 位置数组修改
Using Positional Operator:
使用位置操作符:
$: Allows modification of an array element without knowing its index.$:允许在不知道数组元素索引的情况下修改它。- Example: Increment votes for the first comment:
- 示例:为第一条评论增加投票数:
1
db.blog.updateOne({"post" : post_id}, {"$inc" : {"comments.0.votes" : 1}});
📚 Working with MongoDB
📚 使用 MongoDB
📝 Key Operations
📝 关键操作
- CRUD Operations:
- CRUD 操作:
- Create: Inserting documents using
insertOneandinsertMany. - 创建:使用
insertOne和insertMany插入文档。 - Read: Retrieving data with the
findmethod. - 读取:使用
find方法检索数据。 - Update: Modifying existing documents using
updateOneandupdateMany. - 更新:使用
updateOne和updateMany修改现有文档。 - Delete: Removing documents with
deleteOneanddeleteMany. - 删除:使用
deleteOne和deleteMany删除文档。
- Create: Inserting documents using
🔄 Updating Documents
🔄 更新文档
UpdateOne:
UpdateOne:
Updates only the first document that matches the filter.
仅更新与筛选器匹配的第一个文档。
Example:
示例:
1
db.blog.updateOne({"comments.author": "John"}, {"$set": {"comments.$.author": "Jim"}})
UpdateMany:
UpdateMany:
Updates all documents matching the filter.
更新所有与筛选器匹配的文档。
Use for bulk updates, e.g., giving gifts to users with a specific birthday:
用于批量更新,例如,向具有特定生日的用户赠送礼物:
1
db.users.updateMany({"birthday": "10/13/1978"}, {"$set": {"gift": "Happy Birthday!"}})
⚙️ Upserts
⚙️ Upsert 操作
Upsert is a combination of update and insert. If no document matches the filter, a new document is created.
Upsert 是更新和插入的组合。如果没有文档与筛选器匹配,则会创建一个新文档。
Example:
示例:
1
db.analytics.updateOne({"url": "/blog"}, {"$inc": {"pageviews": 1}}, {"upsert": true})
Benefits:
好处:
- Reduces database round trips.
- 减少数据库往返次数。
- Simplifies code and prevents race conditions.
- 简化代码并防止竞争条件。
✏️ Setting Fields on Insert
✏️ 插入时设置字段
$setOnInsert: Sets a value only when a new document is created.
$setOnInsert:仅在创建新文档时设置值。
Example:
示例:
1
db.users.updateOne({}, {"$setOnInsert": {"createdAt": new Date()}}, {"upsert": true})
📅 Schemas and Data Modeling
📅 模式和数据建模
- Schemas organize and represent data efficiently, ensuring data integrity and optimizing performance.
- 模式有效地组织和表示数据,确保数据完整性并优化性能。
- Data modeling in MongoDB allows for flexible and scalable solutions.
- MongoDB 中的数据建模允许灵活且可扩展的解决方案。
📌 Summary of Key Points
📌 关键点总结
- CRUD operations are fundamental for managing data in MongoDB.
- CRUD 操作是管理 MongoDB 中数据的基础。
- Upserts provide a powerful way to insert or update documents in a single operation.
- Upsert 操作提供了一种在单个操作中插入或更新文档的强大方法。
- Understanding how to use
$setOnInsertcan enhance your data management capabilities. - 理解如何使用
$setOnInsert可以增强您的数据管理能力。 - Using
updateManyallows for efficient bulk updates across multiple documents. - 使用
updateMany可以高效地对多个文档进行批量更新。