使用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
英文地址,請注明出處:http://en.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;然后…