当前位置: 首页 > article >正文

MongoDB(45) 嵌入式文档与引用的优缺点是什么?

嵌入式文档Embedded Documents和引用References是MongoDB中常用的两种数据建模方式它们各有优缺点。选择使用哪种方式取决于具体的应用场景和需求。嵌入式文档优点读取效率高嵌入式文档通常可以在一次查询中获取所有相关数据减少了数据库查询次数。事务一致性由于所有相关数据都在同一个文档中更新时可以保证数据的一致性不需要担心分布式事务问题。简单性数据模型简单查询和处理方便。缺点文档大小限制MongoDB文档大小限制为16MB嵌入式文档如果过大可能会超过这个限制。冗余数据在一些场景下嵌入式文档会导致数据冗余增加存储空间。更新效率低如果嵌入的数据结构复杂更新可能会变得比较繁琐和低效。引用优点数据去重引用方式将数据分离到不同的集合中减少了数据冗余。灵活性高各个集合独立更新灵活性更高适合复杂的数据模型。文档大小分离因为数据被分离到不同的文档中不会受到单个文档大小的限制。缺点查询效率低需要多次查询才能获取所有相关数据特别是在大数据量下查询效率可能较低。事务一致性差跨集合的更新操作不能保证原子性需要额外处理事务一致性问题。复杂性高数据模型复杂需要处理数据的关联和联合查询。使用示例以下示例展示了在Node.js中如何使用嵌入式文档和引用并对比它们的优缺点。安装MongoDB的Node.js驱动npminstallmongodb嵌入式文档示例插入数据const{MongoClient}require(mongodb);asyncfunctioninsertEmbeddedData(){consturimongodb://localhost:27017;constclientnewMongoClient(uri,{useUnifiedTopology:true});try{awaitclient.connect();constdbclient.db(myDatabase);constusersCollectiondb.collection(users);awaitusersCollection.deleteMany({});// 清空集合awaitusersCollection.insertMany([{userId:1,name:Alice,address:{street:123 Main St,city:New York,state:NY,zip:10001},orders:[{orderId:101,amount:50.5,date:newDate(2022-01-01)},{orderId:102,amount:100.0,date:newDate(2022-02-01)}]},{userId:2,name:Bob,address:{street:456 Maple Ave,city:San Francisco,state:CA,zip:94101},orders:[{orderId:103,amount:75.0,date:newDate(2022-01-15)},{orderId:104,amount:200.0,date:newDate(2022-03-01)}]}]);console.log(Embedded data inserted);}finally{awaitclient.close();}}insertEmbeddedData().catch(console.error);查询数据asyncfunctionqueryEmbeddedData(){consturimongodb://localhost:27017;constclientnewMongoClient(uri,{useUnifiedTopology:true});try{awaitclient.connect();constdbclient.db(myDatabase);constusersCollectiondb.collection(users);// 查询某个用户及其所有订单console.log(\nQuery a user and their orders:);letuserawaitusersCollection.findOne({name:Alice});console.log(user);}finally{awaitclient.close();}}queryEmbeddedData().catch(console.error);嵌入式文档的查询效率很高因为所有数据都在同一个文档中。引用示例插入数据const{MongoClient,ObjectId}require(mongodb);asyncfunctioninsertReferencedData(){consturimongodb://localhost:27017;constclientnewMongoClient(uri,{useUnifiedTopology:true});try{awaitclient.connect();constdbclient.db(myDatabase);constusersCollectiondb.collection(users);constordersCollectiondb.collection(orders);awaitusersCollection.deleteMany({});// 清空用户集合awaitordersCollection.deleteMany({});// 清空订单集合// 插入用户数据constusersawaitusersCollection.insertMany([{name:Alice},{name:Bob}]);// 插入订单数据并使用用户的ObjectId作为引用awaitordersCollection.insertMany([{userId:users.insertedIds[0],amount:50.5,date:newDate(2022-01-01)},{userId:users.insertedIds[0],amount:100.0,date:newDate(2022-02-01)},{userId:users.insertedIds[1],amount:75.0,date:newDate(2022-01-15)},{userId:users.insertedIds[1],amount:200.0,date:newDate(2022-03-01)}]);console.log(Referenced data inserted);}finally{awaitclient.close();}}insertReferencedData().catch(console.error);查询数据asyncfunctionqueryReferencedData(){consturimongodb://localhost:27017;constclientnewMongoClient(uri,{useUnifiedTopology:true});try{awaitclient.connect();constdbclient.db(myDatabase);constusersCollectiondb.collection(users);constordersCollectiondb.collection(orders);// 查询某个用户及其所有订单console.log(\nQuery a user and their orders:);letuserawaitusersCollection.findOne({name:Alice});letordersawaitordersCollection.find({userId:user._id}).toArray();console.log({user,orders});// 查询所有订单及其对应的用户信息console.log(\nQuery all orders and their corresponding users:);letresultsawaitordersCollection.aggregate([{$lookup:{from:users,// 要关联的集合localField:userId,// orders 集合中的字段foreignField:_id,// users 集合中的字段as:user// 输出数组字段}},{$unwind:$user// 展开数组}]).toArray();console.log(results);}finally{awaitclient.close();}}queryReferencedData().catch(console.error);通过这些示例我们可以看到两种数据建模方式在操作上的不同嵌入式文档适用于小型数据集和简单的数据关系读取效率高数据一致性好但是在数据量大或者关系复杂的情况下会导致文档过大更新效率低。引用适用于大型数据集和复杂的数据关系数据去重和独立更新灵活但查询效率低特别是在需要多次查询获取相关数据时。此外跨集合的事务一致性需要额外处理。选择合适的数据建模方式取决于具体的应用场景和需求。对于一些应用可以混合使用这两种方式结合它们的优点达到最佳的性能和灵活性。

相关文章:

MongoDB(45) 嵌入式文档与引用的优缺点是什么?

嵌入式文档(Embedded Documents)和引用(References)是MongoDB中常用的两种数据建模方式,它们各有优缺点。选择使用哪种方式取决于具体的应用场景和需求。 嵌入式文档 优点 读取效率高:嵌入式文档通常可以在…...

MiniGrid 开源项目教程

MiniGrid 开源项目教程 【免费下载链接】minigrid 📏 Minimal 2kb zero dependency cascading grid layout 项目地址: https://gitcode.com/gh_mirrors/min/minigrid 1. 项目的目录结构及介绍 MiniGrid 项目的目录结构如下: minigrid/ ├── R…...

【亲测免费】 keyring:Python 密钥存储解决方案

keyring:Python 密钥存储解决方案 【免费下载链接】keyring 项目地址: https://gitcode.com/gh_mirrors/ke/keyring 项目介绍 keyring 是一个 Python 库,旨在安全地管理应用程序中的密码和其他敏感信息。它利用系统提供的密钥保管库服务&#x…...

【亲测免费】 MiniGrid 开源项目实战指南

MiniGrid 开源项目实战指南 【免费下载链接】minigrid 📏 Minimal 2kb zero dependency cascading grid layout 项目地址: https://gitcode.com/gh_mirrors/min/minigrid 项目介绍 MiniGrid 是一个轻量级的环境库,专为强化学习(Reinfo…...

【亲测免费】 DockerGS 开源项目安装与使用教程

DockerGS 开源项目安装与使用教程 【免费下载链接】DockerGS DockerGC is a container that run Grasscutter (anime game) with just a single command. 项目地址: https://gitcode.com/gh_mirrors/do/DockerGS 项目概述 DockerGS 是一个基于 GitHub 的开源项目&#…...

TNWX 开源项目教程

TNWX 开源项目教程 【免费下载链接】TNWX TNWX: TypeScript Node.js WeiXin 微信系开发脚手架,支持微信公众号、微信支付、微信小游戏、微信小程序、企业微信/企业号。最最最重要的是能快速的集成至任何 Node.js 框架(Express、Nest、Egg、Koa 等) 项目地址: ht…...

【亲测免费】 WunderGraph 开源项目教程

WunderGraph 开源项目教程 【免费下载链接】wundergraph WunderGraph is a Backend for Frontend Framework to optimize frontend, fullstack and backend developer workflows through API Composition. 项目地址: https://gitcode.com/gh_mirrors/wu/wundergraph 1. …...

【免费下载】 CreamInstaller:自动DLC解锁器安装与配置生成器

CreamInstaller:自动DLC解锁器安装与配置生成器 【免费下载链接】CreamInstaller Automatically finds all installed Steam, Epic and Ubisoft games with their respective DLC-related DLL locations on the users computer, parses SteamCMD, Steam Store and E…...

【免费下载】 CreamInstaller 使用教程

CreamInstaller 使用教程 【免费下载链接】CreamInstaller Automatically finds all installed Steam, Epic and Ubisoft games with their respective DLC-related DLL locations on the users computer, parses SteamCMD, Steam Store and Epic Games Store for user-selecte…...

CreamInstaller 项目安装与使用教程

CreamInstaller 项目安装与使用教程 【免费下载链接】CreamInstaller Automatically finds all installed Steam, Epic and Ubisoft games with their respective DLC-related DLL locations on the users computer, parses SteamCMD, Steam Store and Epic Games Store for us…...

0x0 开源项目安装与使用指南

0x0 开源项目安装与使用指南 【免费下载链接】0x0 No-bullshit file hosting and URL shortening service. Mirror of https://git.0x0.st/mia/0x0 项目地址: https://gitcode.com/gh_mirrors/0x/0x0 1. 项目目录结构及介绍 0x0 是一个简约型的文件托管与URL缩短服务&a…...

网络的历史及socket接口了解

一、网络发展历史 (这一部分只是了解一下即可) 在最开始,每一台计算机都是独立的计算机,如果我们两个人需要协同作业,都需要一个人先做一部分,然后拷贝下来,到另外一台主机上交由另外一…...

LTECleanerFOSS 项目推荐

LTECleanerFOSS 项目推荐 【免费下载链接】LTECleanerFOSS The last Android cleaner youll ever need! 项目地址: https://gitcode.com/gh_mirrors/lt/LTECleanerFOSS 项目基础介绍 LTECleanerFOSS 是一个开源项目,旨在清理和优化 LTE 网络相关的数据。该项…...

开源项目推荐:Polyfill Library

开源项目推荐:Polyfill Library 【免费下载链接】polyfill-library NodeJS module to create polyfill bundles tailored to individual user-agents. 项目地址: https://gitcode.com/gh_mirrors/pol/polyfill-library 1. 项目基础介绍 Polyfill Library 是…...

硬件加速视频转码工具:基于Android MediaCodec API的Transcoder项目推荐

硬件加速视频转码工具:基于Android MediaCodec API的Transcoder项目推荐 【免费下载链接】Transcoder 🎞 Hardware-accelerated video transcoding using Android MediaCodec APIs. Supports cropping, concatenation, clipping, audio processing, vide…...

10分钟上手!REST API自动化测试神器:从测试到文档一键搞定

10分钟上手!REST API自动化测试神器:从测试到文档一键搞定 【免费下载链接】rest-client A tool for automated testing REST API, generating exquisite testing report and REST API documentation. 项目地址: https://gitcode.com/gh_mirrors/rest/…...

Django-Dynamic-Scraper入门教程:从零开始构建你的第一个动态爬虫

Django-Dynamic-Scraper入门教程:从零开始构建你的第一个动态爬虫 【免费下载链接】django-dynamic-scraper Creating Scrapy scrapers via the Django admin interface 项目地址: https://gitcode.com/gh_mirrors/dj/django-dynamic-scraper Django-Dynamic…...

go-wkhtmltopdf在AWS Lambda中的应用:无服务器PDF生成方案

go-wkhtmltopdf在AWS Lambda中的应用:无服务器PDF生成方案 【免费下载链接】go-wkhtmltopdf Golang commandline wrapper for wkhtmltopdf 项目地址: https://gitcode.com/gh_mirrors/go/go-wkhtmltopdf go-wkhtmltopdf是一个Golang命令行包装器,…...

【亲测免费】 IBAN.js - 国际银行账号验证与格式化工具

IBAN.js - 国际银行账号验证与格式化工具 【免费下载链接】iban.js IBAN & BBAN validation, formatting and conversion in Javascript 项目地址: https://gitcode.com/gh_mirrors/ib/iban.js 1. 项目基础介绍与主要编程语言 IBAN.js 是一个开源的JavaScript库&am…...

ARM64架构手动编译libtorch,安装MKL/oneDNN加速模型推理,详细流程!

目录 前言: 一、依赖环境 二、下载pytorch源码 三、下载oneDNN源码 三、编译libtorch 四、整理libtorch 五、C调用libtorch 前言: libtorch官方并没有给出ARM64架构的安装文件,在ARM64环境下,libtorch需要手动编译。编译完成…...

简易CPU设计入门:内存读写(五)

专栏导航 上一篇:简易CPU设计入门:内存读写(四) 专栏目录 下一篇:无 项目代码下载 请大家首先准备好本项目所用的源代码。如果已经下载了,那就不用重复下载了。如果还没有下载,那么&#xf…...

JAVA软件开发岗位高频技术面筋(持续更新)

一.jdk8 特性 1.Lambda表达式 使用匿名内部类处理,减少内部类的编写,提高系统可读性。支持函数式编程。 2.Stream API 流操作数据时,外部变量声明为final,确保变量在Lambda表达式中不被修改。 支持并行流,实现原理多线…...

roop-unleashed 项目亮点解析

roop-unleashed 项目亮点解析 【免费下载链接】roop-unleashed Evolved Fork of roop with Web Server and lots of additions 项目地址: https://gitcode.com/gh_mirrors/ro/roop-unleashed 1. 项目的基础介绍 roop-unleashed 是一个开源项目,旨在提供一个…...

roop-unleashed 的项目扩展与二次开发

roop-unleashed 的项目扩展与二次开发 【免费下载链接】roop-unleashed Evolved Fork of roop with Web Server and lots of additions 项目地址: https://gitcode.com/gh_mirrors/ro/roop-unleashed 1、项目的基础介绍 roop-unleashed 是一个开源项目,旨在…...

开源项目 Adobe-GenP 亮点详解

开源项目 Adobe-GenP 亮点详解 【免费下载链接】Adobe-GenP Adobe CC 2019/2020/2021/2022/2023 GenP Universal Patch 3.0 项目地址: https://gitcode.com/gh_mirrors/ad/Adobe-GenP 1. 项目的基础介绍 Adobe-GenP 是一个开源项目,旨在为用户提供一个高效的…...

开源项目 Adobe-GenP 的扩展与二次开发潜力

开源项目 Adobe-GenP 的扩展与二次开发潜力 【免费下载链接】Adobe-GenP Adobe CC 2019/2020/2021/2022/2023 GenP Universal Patch 3.0 项目地址: https://gitcode.com/gh_mirrors/ad/Adobe-GenP 1. 项目的基础介绍 Adobe-GenP 是一个开源项目,旨在提供一种…...

【跟韩工学Ubuntu第2课】 第2章 磁盘、LVM、文件系统与扩容备份-001篇】

文章目录《Linux系统管理与服务配置》第2章 磁盘、LVM、文件系统与扩容备份2.1 磁盘基础:分区与分区表2.2 实战1:磁盘分区实操2.3 实战2:LVM逻辑卷管理2.4 实战3:文件系统管理2.5 实战4:磁盘扩容与数据备份2.6 课后习题…...

AI系列:AI时代必懂的基础概念扫盲

目录 第一篇章:核心概念三兄弟 1. 人工智能(AI):让机器模仿人的智能 2. 机器学习(ML):实现AI的一种方法 3. 深度学习(DL):机器学习中非常强大的一种技术 …...

linux系统 Ventoy 制作U启

比起君子讷于言而敏于行,我更喜欢君子善于言且敏于行。 目录 1. 下载 Ventoy 2. 解压压缩包 3. 插入U盘并确认设备名 4. 安装Ventoy到U盘(会格式化U盘) 5. 复制ISO文件 6. 使用启动盘 Ventoy的优点 1. 下载 Ventoy wget https://github.com/v…...

Webpack5 处理 CSS文件

1、背景Webpack 本身仅能处理Js文件,无法识别CSS文件及代码。因此需在webpack.config.js文件中进行单独处理。2、基础框架搭建1、搭建简单项目框架执行 npm install -y 指令,生成 package.json文件执行 npm install webpack webpack-cli html-webpack-pl…...