使用FastAPI和React以及MongoDB构建全栈Web应用04 MongoDB快速入门

一、NoSQL 概述

1.1 了解关系数据库的局限性

Before diving into NoSQL, it’s essential to understand the challenges posed by traditional Relational Database Management Systems (RDBMS). While RDBMS have been the cornerstone of data management for decades, they face limitations when dealing with massive datasets, complex data structures, and high-performance demands.

  • Scalability Issues: RDBMS often struggle with horizontal scaling, making it challenging to handle increasing data volumes and user loads.
  • Data Structure Rigidity: The rigid schema of RDBMS can hinder flexibility, especially when dealing with rapidly evolving data structures.
  • Complex Queries: Complex queries on large datasets can be computationally expensive and slow in RDBMS.

在深入研究 NoSQL 之前,了解传统关系数据库管理系统 (RDBMS) 带来的挑战至关重要。虽然 RDBMS 几十年来一直是数据管理的基石,但在处理海量数据集、复杂数据结构和高性能需求时,它们面临着限制。

  • 可扩展性问题: RDBMS 经常难以进行水平扩展,这使得处理不断增长的数据量和用户负载变得具有挑战性。
  • 数据结构刚性: RDBMS 的僵化架构会阻碍灵活性,尤其是在处理快速发展的数据结构时。
  • 复杂查询:在 RDBMS 中,对大型数据集的复杂查询可能计算成本高昂且速度缓慢。

1.2 什么是NoSQL?

NoSQL, which stands for “Not Only SQL,” is a broad category of database management systems that offer alternatives to traditional relational databases. These databases are designed to handle large volumes of unstructured or semi-structureddata with high performance and scalability.

NoSQL 代表“不仅仅是 SQL”,是一大类数据库管理系统,可替代传统的关系数据库。这些数据库旨在以高性能和可扩展性处理大量非结构化或半结构化数据。

Key Characteristics of NoSQL Databases:

  • Flexible Data Models: NoSQL databases support various data models, including document, key-value, wide-column, and graph, allowing for more adaptable data structures.
  • Scalability: They excel at horizontal scaling, enabling you to distribute data across multiple servers to handle increasing loads.
  • High Performance: NoSQL databases are often optimized for fast read and write operations, making them suitable for real-time applications.
  • Distributed Systems: Many NoSQL databases are designed for distributed environments, providing fault tolerance and high availability.

NoSQL 数据库的主要特点:

  • 灵活的数据模型:NoSQL 数据库支持各种数据模型,包括文档、键值、宽列和图形,允许使用更具适应性的数据结构。
  • 可扩展性: 它们擅长水平扩展,使您能够在多个服务器之间分配数据以处理不断增加的负载。
  • 高性能: NoSQL 数据库通常针对快速读写操作进行了优化,使其适用于实时应用程序。
  • 分布式系统: 许多 NoSQL 数据库都是为分布式环境设计的,提供容错和高可用性。

1.3 NoSQL 数据库类型

Document Databases:

  • Store data in flexible JSON-like documents.
  • Examples: MongoDB, Couchbase
  • Ideal for: Content management systems, user profiles, and application data.

文档数据库:

  • 将数据存储在灵活的类似 JSON 的文档中。
  • 示例:MongoDB、Couchbase
  • 适用于:内容管理系统、用户配置文件和应用程序数据。

Key-Value Stores:

  • Store data as simple key-value pairs.
  • Examples: Redis, Amazon DynamoDB
  • Ideal for: Session management, caching, and high-performance counters.

键值存储:

  • 将数据存储为简单的键值对。
  • 示例:Redis、Amazon DynamoDB
  • 适用于:会话管理、缓存和高性能计数器。

Wide-Column Stores:

  • Store data in columns, allowing for flexible schema and efficient data retrieval.
  • Examples: Cassandra, HBase
  • Ideal for: Time-series data, analytics, and large-scale data processing.

宽列存储:

  • 将数据存储在列中,从而实现灵活的架构和高效的数据检索。
  • 示例:Cassandra、HBase
  • 适用于:时间序列数据、分析和大规模数据处理。

Graph Databases:

  • Store data as nodes and relationships between them.
  • Examples: Neo4j, Amazon Neptune
  • Ideal for: Social networks, recommendation systems, and fraud detection.

图形数据库:

  • 将数据存储为节点以及它们之间的关系。
  • 示例:Neo4j、Amazon Neptune
  • 适用于: 社交网络、推荐系统和欺诈检测。

1.4 MongoDB数据库

MongoDB, a document-oriented NoSQL database, is widely used in web applications. Its flexibility, scalability, and rich feature set make it a popular choice for developers.

MongoDB 是一种面向文档的 NoSQL 数据库,广泛用于 Web 应用程序。它的灵活性、可扩展性和丰富的功能集使其成为开发人员的热门选择。

Basic MongoDB Concepts:

  • Database: A container for collections.
  • Collection: A group of documents.
  • Document: A JSON-like structure representing a record.

基本 MongoDB 概念:

  • 数据库: 集合的容器。
  • 集合: 一组文档。
  • 文档:表示记录的类似 JSON 的结构。

1.5 MongoDB 使用步骤

To build a web application using FastAPI, React, and MongoDB, you’ll typically follow these steps:

要使用 FastAPI、React 和 MongoDB 构建 Web 应用程序,您通常需要遵循以下步骤:

Set up the MongoDB environment: Install MongoDB and create a database.

设置 MongoDB 环境:安装 MongoDB 并创建数据库。

Create a FastAPI backend:

  • Install required libraries: fastapi, pymongo, uvicorn
  • Establish a connection to the MongoDB database:

创建一个 FastAPI 后端:

  • 安装所需的库:fastapi、pymongo、uvicorn
  • 建立与 MongoDB 数据库的连接:

Create a React frontend:

  • Use a library like axios to make requests to the FastAPI backend.
  • Display data retrieved from the backend.
  • Allow users to create and update data.

创建一个 React 前端:

  • 使用像 axios 这样的库向 FastAPI 后端发出请求。
  • 显示从后端检索到的数据。
  • 允许用户创建和更新数据。

1.6 使用 NoSQL 的优势

Advantages of Using NoSQL

  • Scalability: Handle massive datasets and high traffic efficiently.
  • Flexibility: Adapt to changing data structures without major schema modifications.
  • Performance: Achieve fast read and write operations.
  • Cost-effectiveness: Often lower hardware and maintenance costs compared to RDBMS.

使用 NoSQL 的优势

  • 可扩展性:高效处理海量数据集和高流量。
  • 灵活性:适应不断变化的数据结构,无需进行重大架构修改。
  • 性能:实现快速读写作。
  • 成本效益:与 RDBMS 相比,通常更低的硬件和维护成本。

1.7 何时使用 NoSQL

When to Use NoSQL

  • Large volumes of unstructured or semi-structured data.
  • High write throughput and low latency requirements.
  • Complex data structures that evolve over time.
  • Horizontal scalability needs.

何时使用 NoSQL

  • 大量非结构化或半结构化数据。
  • 高写入吞吐量和低延迟要求。
  • 随时间演变的复杂数据结构。
  • 水平可扩展性需求。

NoSQL databases offer a powerful and flexible alternative to traditional relational databases. By understanding the different types of NoSQL databases and their use cases, you can make informed decisions about when and how to leverage them in your web applications. MongoDB, with its document-oriented model, is a popular choice for many developers due to its ease of use and scalability.

NoSQL 数据库为传统关系数据库提供了强大而灵活的替代方案。通过了解不同类型的 NoSQL 数据库及其使用案例,您可以就何时以及如何在 Web 应用程序中利用它们做出明智的决策。MongoDB 具有面向文档的模型,由于其易用性和可扩展性,是许多开发人员的热门选择。

For our web application, we’ll focus on MongoDB as our NoSQL database. It’s a popular choice due to its flexibility, scalability, and ease of use. Let’s consider a simple blog application as an example.

对于我们的 Web 应用程序,我们将重点关注 MongoDB 作为我们的 NoSQL 数据库。由于其灵活性、可扩展性和易用性,它是一个受欢迎的选择。让我们以一个简单的博客应用程序为例。

1.8 博客列表实战

Before we start coding, let’s define our data structure. In MongoDB, we use collections to store similar documents. For our blog, we might have collections for:

  • posts: Stores blog posts with title, content, author, creation date, etc.
  • users: Stores user information like username, email, password, etc.
  • comments: Stores comments for each post with comment text, author, and timestamp.

在开始编码之前,我们先定义一下数据结构。在 MongoDB 中,我们使用集合来存储类似的文档。对于我们的博客,我们可能有以下集合:

  • posts:存储包含标题、内容、作者、创建日期等的博客文章。
  • users:存储用户名、电子邮件、密码等用户信息。
  • comments:存储每个帖子的评论以及评论文本、作者和时间戳。

后端代码:

from bson import ObjectId
from fastapi import FastAPI, HTTPException
from pymongo import MongoClient
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModelapp = FastAPI()
# MongoDB 连接对象
client = MongoClient("mongodb://zhangdapeng:zhangdapeng520@localhost:27017/")
# 数据库
db = client["blog_db"]
# 博客集合
posts = db["posts"]
# 用户集合
users = db["users"]
# 评论集合
comments = db["comments"]# 配置跨域
app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],
)class Post(BaseModel):"""博客模型"""# 标题title: str# 内容content: str# 作者author: str# 创建时间created_at: strclass User(BaseModel):"""用户模型"""# 用户名username: str# 邮箱email: str# 密码password: strclass Comment(BaseModel):"""评论模型"""# 博客IDpost_id: str# 作者author: str# 评论文本text: str# 评论时间created_at: str@app.post("/posts", summary="创建博客", description="创建一个新的博客")
async def create_post(post: Post):result = posts.insert_one(post.dict())return {"post_id": str(result.inserted_id)}@app.get("/posts", summary="获取所有博客", description="获取所有博客")
async def get_posts():all_posts = list(posts.find())data = []for post in all_posts:post["_id"] = str(post["_id"])data.append(post)return dataif __name__ == '__main__':import uvicornuvicorn.run(app, host="0.0.0.0", port=8080)

测试JSON:

{"title": "测试博客","content": "今天学习了fastapi+React前后端分离开发","author": "源滚滚编程","created_at": "2025-05-10 12:33:33"
}

前端渲染:

import {useEffect, useState} from "react";
import axios from "axios";function App() {// 博客列表数据const [posts, setPosts] = useState([]);// 会在页面加载时执行useEffect(() => {axios.get('http://localhost:8080/posts').then(res => {console.log("fastapi传过来的数据", res.data)setPosts(res.data);}).catch(err => {console.log(err);});}, [])return (<><div><h1>博客列表</h1><div>{posts.map((blog) => (<div key={blog._id} className="blog-card"><h2>{blog.title}</h2><p>{blog.content}</p><p>作者: {blog.author}</p><p>创建时间: {blog.created_at}</p></div>))}</div></div></>)
}export default App

Key Advantages of Using MongoDB in this Scenario

  • Flexible data structure: Easily adapt to changes in post or user information.
  • Scalability: Handle increasing numbers of posts, users, and comments efficiently.
  • Performance: MongoDB is optimized for fast read and write operations.
  • Rich query language: MongoDB’s query language allows for complex data retrieval.

在此场景中使用 MongoDB 的主要优势

  • 灵活的数据结构: 轻松适应帖子或用户信息的变化。
  • 可扩展性:有效处理越来越多的帖子、用户和评论。
  • 性能:MongoDB 针对快速读写作进行了优化。
  • 丰富的查询语言:MongoDB 的查询语言允许复杂的数据检索。

Additional Considerations

  • Indexing: Create appropriate indexes to improve query performance.
  • Data validation: Use Pydantic or built-in MongoDB validation for data integrity.
  • Security: Implement proper authentication and authorization mechanisms.
  • Error handling: Handle potential errors gracefully.

其他注意事项

  • 索引:创建适当的索引以提高查询性能。
  • 数据验证:使用 Pydantic 或内置 MongoDB 验证来实现数据完整性。
  • 安全性:实施适当的身份验证和授权机制。
  • 错误处理:妥善处理潜在错误。

二、理解MongoDB

2.1 什么是 MongoDB

MongoDB is a popular NoSQL database that uses a document-oriented data model. Unlike traditional relational databases, which store data in tables, MongoDB stores data in flexible, JSON-like documents. This provides significant advantages in terms of scalability, performance, and ease of development.

MongoDB 是一种流行的 NoSQL 数据库,它使用面向文档的数据模型。与将数据存储在表中的传统关系数据库不同,MongoDB 将数据存储在灵活的类似 JSON 的文档中。这在可伸缩性、性能和易开发性方面提供了显著的优势。

Core Concepts

  • Document: A fundamental unit of data storage in MongoDB. It’s a key-value pair structure similar to JSON.
  • Collection: A group of documents. Think of it as a table in a relational database.
  • Database: A container for collections.

核心概念

  • 文档:MongoDB 中数据存储的基本单元。它是一个类似于 JSON 的键值对结构。
  • 集合:一组文档。将其视为关系数据库中的表。
  • 数据库:集合的容器。

2.2 MongoDB 的灵活性

One of the key strengths of MongoDB is its flexible schema. This means you don’t need to define a rigid structure for your documents upfront. You can add or remove fields as needed, making it ideal

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/904952.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/904952.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

高精度之加减乘除之多解总结(加与减篇)

开篇总述&#xff1a;精度计算的教学比较杂乱&#xff0c;无系统的学习&#xff0c;且存在同法多线的方式进行同一种运算&#xff0c;所以我写此篇的目的只是为了直指本质&#xff0c;不走教科书方式&#xff0c;步骤冗杂。 一&#xff0c;加法 我在此讲两种方法&#xff1a; …

气象大模型光伏功率预测中的应用:从短期,超短期,中长期的实现与开源代码详解

1. 引言 光伏功率预测对于电力系统调度、能源管理和电网稳定性至关重要。随着深度学习技术的发展,大模型(如Transformer、LSTM等)在时间序列预测领域展现出强大能力。本文将详细介绍基于大模型的光伏功率预测方法,涵盖短期(1-6小时)、超短期(15分钟-1小时)和中长期(1天-1周…

玩转Docker(一):基本概念

容器技术是继大数据和云计算之后又一炙手可热的技术&#xff0c;而且未来相当一段时间内都会非常流行。 本文将对其基本概念和基本使用做出介绍。包括容器生态系统、容器的原理、怎样运行第一个容器、容器技术的概念与实践、Docker镜像等等 目录 一. 鸟瞰容器生态系统 1. 容器…

计算机视觉与深度学习 | 基于数字图像处理的裂缝检测与识别系统(matlab代码)

🍅🍅🍅🍅🍅🍅🍅🍅🍅🍅🍅🍅🍅🍅🍅🍅 基于数字图像处理的裂缝检测与识别系统 🥦🥦🥦🥦🥦🥦🥦🥦🥦🥦🥦🥦🥦**系统架构设计****1. 图像预处理**目标:消除噪声+增强裂缝特征**2. 图像分割**目标:提取裂缝区域**3. 特征…

推荐一款免费开源工程项目管理系统软件,根据工程项目全过程管理流程开发的OA 办公系统

在当今的工程项目管理领域&#xff0c;许多企业和团队面临着诸多难题。传统的管理方式往往依赖于人工记录和分散的工具&#xff0c;导致项目进度难以实时把控&#xff0c;任务分配不够清晰&#xff0c;合同管理混乱&#xff0c;事件提醒不及时&#xff0c;财务管理缺乏系统性&a…

Proser:在使用中改进

上位机接收到下位机发送的协议&#xff0c;解析出工作模式&#xff0c;然后依据此模式切换到相应的界面。为了调试这个功能&#xff0c;由Proser提供的Block与Sequence生成器相当有用&#xff1a; 使用Block生成器&#xff1a;忽略掉不感兴趣的数据使用Sequence生成器&#xf…

C语言_程序的段

在 C 语言程序中,内存通常被分为多个逻辑段,每个段存储不同类型的数据。理解这些段的结构和功能,有助于你更高效地编写、调试和优化程序。以下是 C 语言程序中主要的内存段及其特点: 1. 代码段(Text Segment) 存储内容:编译后的机器指令(程序代码)。特性: 只读:防止…

【桌面】【输入法】常见问题汇总

目录 一、麒麟桌面系统输入法概述 1、输入法介绍 2、输入法相关组件与服务 3、输入法调试相关命令 3.1、输入法诊断命令 3.2、输入法配置重新加载命令 3.3、启动fcitx输入法 3.4、查看输入法有哪些版本&#xff0c;并安装指定版本 3.5、重启输入法 3.6、查看fcitx进程…

Node.js 24.0 正式发布:性能跃升与开发体验全面升级

Node.js v24.0.0 震撼发布&#xff01;V8 13.6、npm 11、权限模型稳定化等重磅更新 2025年5月6日 —— Node.js 社区迎来重大里程碑&#xff01;Node.js v24.0.0 正式发布&#xff0c;带来一系列激动人心的新特性、性能优化和 API 改进。本次更新涵盖 V8 JavaScript 引擎升级至…

MySQL 查询优化全攻略:从原理到实战

为什么查询优化如此重要&#xff1f; 在当今数据驱动的时代&#xff0c;数据库性能直接影响着用户体验和业务效率。根据统计&#xff0c;网页加载时间每增加1秒&#xff0c;转化率可能下降7%&#xff0c;而数据库查询往往是性能瓶颈的关键所在。作为最流行的开源关系型数据库之…

《从零开始:构建你的第一个区块链应用》

一、引言 区块链技术&#xff0c;这个曾经只在金融领域被广泛讨论的技术&#xff0c;如今已经渗透到各个行业。从供应链管理到智能合约&#xff0c;区块链的应用场景越来越丰富。对于开发者来说&#xff0c;理解区块链的基本原理并构建一个简单的区块链应用&#xff0c;是进入这…

使用AES-CBC + HMAC-SHA256实现前后端请求安全验证

AES-CBC HMAC-SHA256 加密验证方案&#xff0c;下面是该方案二等 优点 与 缺点 表格&#xff0c;适用于文档、评审或技术选型说明。 ✅ 优点表格&#xff1a;AES-CBC HMAC-SHA256 加密验证方案 类别优点说明&#x1f510; 安全性使用 AES-CBC 对称加密使用 AES-128-CBC 是可…

Veins同时打开SUMO和OMNeT++的GUI界面

进入 Veins 工程目录&#xff08;即包含 sumo-launchd.py 的目录&#xff09;&#xff0c;打开终端设置 SUMO_HOME 环境变量&#xff08;指向你安装的 SUMO 路径&#xff09;&#xff1a; export SUMO\_HOME/home/veins/src/sumo-1.11.0编译 Veins 工程&#xff08;包含 OMNeT…

suricata之日志截断

一、背景 在suricata的调试过程中&#xff0c;使用SCLogXXX api进行信息的输出&#xff0c;发现输出的日志被截断了&#xff0c;最开始以为是解析逻辑有问题&#xff0c;没有解析完整&#xff0c;经过排查后&#xff0c;发现SCLogXXX api内部进行了长度限制&#xff0c;最长2K…

navicat 如何导出数据库表 的这些信息 字段名 类型 描述

navicat 如何导出数据库表 的这些信息 字段名 类型 描述 数据库名字 springbootmt74k 表名字 address SELECT COLUMN_NAME AS 字段名,COLUMN_TYPE AS 类型,COLUMN_COMMENT AS 描述 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA springbootmt74k AND TABLE_NAME a…

LVGL图像导入和解码

LVGL版本&#xff1a;8.1 概述 在LVGL中&#xff0c;可以导入多种不同类型的图像&#xff1a; 经转换器生成的C语言数组&#xff0c;适用于页面中不常改变的固定图像。存储系统中的外部图像&#xff0c;比较灵活&#xff0c;可以通过插卡或从网络中获取&#xff0c;但需要配置…

【Web前端开发】HTML基础

Web前端开发是用来直接给用户呈现一个一个的网页&#xff0c;主要包含实现用户的结构&#xff08;HTML&#xff09;、样式&#xff08;CSS&#xff09;、交互&#xff08;JavaScript&#xff09;。然而一个软件通常是由后端和前端完成的。可以查阅文档&#xff1a;HTML 教程 (w…

MySQL 8.0 单节点部署与一主两从架构搭建实战

前言&#xff1a;在数据驱动的时代&#xff0c;数据库作为数据存储与管理的核心组件&#xff0c;其架构的选择与配置对系统的性能、可用性和扩展性至关重要。MySQL 作为一款广泛应用的开源关系型数据库&#xff0c;凭借其稳定的性能和丰富的功能&#xff0c;深受开发者和企业的…

数据库故障排查全攻略:从实战案例到体系化解决方案

一、引言&#xff1a;数据库故障为何是技术人必须攻克的 "心腹大患" 在数字化时代&#xff0c;数据库作为企业核心数据资产的载体&#xff0c;其稳定性直接决定业务连续性。据 Gartner 统计&#xff0c;企业每小时数据库 downtime 平均损失高达 56 万美元&#xff0…

牛客周赛round91

C 若序列为1 4 5 7 9 1 2 3&#xff0c;1 9一定大于1 1或1 4...所以只需要记录当前数之前数字的最大值&#xff0c;然后遍历取max即可&#xff0c;所以对于上面的序列有效的比较为1 9&#xff0c;2 9&#xff0c;3 9取max 代码 //求大于当前数的最大值&#xff0c;然后…