search
HomeBackend DevelopmentPHP TutorialAdvantages and disadvantages of mongodb compared with mysql




Compared with relational databases, MongoDB’s advantages:
① Weak consistency (eventual consistency), which can better ensure user access speed:

传 For example, in the traditional relational database, an operation of a count type locks the data set, which can ensure that the accurate value of the current situation can be obtained. This is important in some cases, such as when checking account information through an ATM, but for Wordnik, the data is constantly updated and growing, and this "accurate" guarantee has almost no meaning, but will have a great impact. Delay. What they need is an "approximate" number and faster processing.

But in some cases MongoDB will lock the database. If there are hundreds of requests at the moment, they can pile up and cause many problems. We use the following optimizations to avoid lock-ins:
Before each update, we will first query the records. Query operations put objects into memory so updates can be as fast as possible. In a master/slave deployment scenario, the slave node can be run with the "-pretouch" parameter, which will achieve the same effect.
Use multiple mongod processes. We split the database into multiple processes based on access patterns.
②The storage method of document structure makes it easier to obtain data.

For a hierarchical data structure, if you want to use a flat, table-like structure to save the data, it will be very difficult to query or obtain the data.


Example 1: Take a "dictionary item" as an example. Although it is not very complicated, it still involves content such as "definition", "part of speech", "pronunciation" or "citation". Most engineers would express this model using primary and foreign keys in a relational database, but wouldn't it be better to think of it as a "document" rather than a "series of related tables"? Using "dictionary.definition.partOfSpeech='noun'" to query is more convenient and faster than a series of complex (and often costly) join queries between tables.

Example 2:
In a relational database, a blog (including article content, comments, and votes for comments) will be scattered across multiple data tables. In MongoDB, a document can be used to represent a blog, with comments and votes as document arrays placed in the main text document. This makes the data easier to manage and eliminates the "JOIN" operations that affect performance and horizontal scalability in traditional relational databases.

CODE↓

> db.blogposts.save({ title : "My First Post", author: {name : "Jane", id :1}, comments : [{ by: "Abe", text: "First" },
                       { by : "Ada", text : "Good post" }]
})
> db.blogposts.find( { "author.name" : "Jane" } )
> db.blogposts.findOne({ title : "My First Post", "author. name": "Jane", comments : [{ by: "Abe", text: "First" },
                         { by : "Ada", text : "Good post" } ]
})
> db.blogposts.find( { "comments.by" : "Ada" } )
> db.blogposts.ensureIndex( { "comments.by" : 1 } );

Example 3:
MongoDB is a document-oriented database currently developed and maintained by 10gen. It is feature-rich and complete and can completely replace MySQL. In the process of using MongoDB for product prototyping, we summarized some of the highlights of MonogDB:

Using JSON style syntax, easy to master and understand: MongoDB uses BSON, a variant of JSON, as the format and syntax for internal storage. All operations on MongoDB use JSON style syntax, and the data submitted or received by the client is displayed in JSON form. Compared with SQL, it is more intuitive, easy to understand and master.

Schema-less, supports embedded subdocuments: MongoDB is a Schema-free document database. A database can have multiple Collections, and each Collection is a collection of Documents. Collection and Document are not equivalent to Table and Row in traditional databases. There is no need to define a Collection in advance and can be created at any time.

Collection can contain document records with different schemas. This means that the document in your previous record has 3 attributes, while the document in the next record can have 10 attributes. The type of the attributes can be either basic data types (such as numbers, strings, dates, etc.) or It can be an array or a hash, or even an embedded document. In this way, a denormalizing data model can be achieved and the query speed can be improved.

③ Built-in GridFS supports large-capacity storage.

GridFS is an excellent distributed file system that can support massive data storage.
It has built-in GridFS and MongoDB, which can meet the fast range query of large data sets.

④Built-in Sharding.

Provides a Range-based Auto Sharding mechanism: a collection can be divided into several segments according to the record range and split into different Shards.

Shards can be combined with replication. Sharding+fail-over can be achieved with Replica sets, and load balancing can be achieved between different Shards. Queries are transparent to the client. The client performs queries, statistics, MapReduce and other operations, which are automatically routed to the back-end data nodes by MongoDB. This allows us to focus on our business and can upgrade painlessly when appropriate. MongoDB's Sharding design capability can support up to about 20 petabytes, which is enough to support general applications.

This ensures that MongoDB runs on a cheap PC server cluster. PC clusters are very convenient and cost-effective to expand, avoiding the complexity and cost of "sharding" operations.

⑤ Rich third-party support. (This is an advantage that MongoDB also has compared to other NoSQL)

Many NoSQL open source databases on the Internet are completely community-based and have no official support, which brings great risks to users.

Behind the open source document database MongoDB is 10gen, a commercial company that provides commercial training and support.

And the MongoDB community is very active, and many development frameworks have quickly provided support for MongoDB. Many well-known large companies and websites are also using MongoDB in production environments. More and more innovative companies are turning to MongoDB as a technical solution to match Django and RoR.

⑥Superior performance:

千 On the occasion of use, tens of millions of document objects, nearly 10g data, query of index IDs will not be slower than mysql, but query on non -index fields will be fully won. Mysql is actually not capable of querying any field in a large amount of data, and the query performance of mongodb really surprised me. The writing performance is also very satisfactory. When writing millions of data, mongodb is much faster than the couchdb I have tried before. It can basically be solved in less than 10 minutes. I would like to add that during the observation process, mongodb is far from being a CPU killer.


Compared with relational databases, MongoDB’s disadvantages:

①mongodb does not support transaction operations.

So systems with strict transaction requirements (such as banking systems) definitely cannot use it. (This point corresponds to advantage ①)
②Mongodb takes up too much space.

About the reasons, in the official FAQ, the following aspects are mentioned:
1. Pre-allocation of space: In order to avoid excessive hard disk fragmentation, mongodb will apply for a large piece of hard disk space every time there is insufficient space, and the amount of application increases exponentially from 64M, 128M, 256M, until 2G is The maximum size of a single file. As the amount of data increases, you can see these files in the data directory with increasing block generation capacity.

2. The space occupied by field names: In order to maintain the structural information in each record for query, mongodb needs to store the key-value of each field in the form of BSON. If the value domain is not large compared to the key domain , such as storing numerical data, the data overhead is the largest. One way to reduce space usage is to make field names as short as possible so that they take up less space, but this requires a trade-off between readability and space usage. I once suggested that the author make the field name an index, and use one byte to represent each field name, so that you don't have to worry about how long the field name is. But the author's concerns are not unreasonable. This indexing method requires the index value to be replaced with the original value after each query results are obtained, and then sent to the client. This replacement is also quite time-consuming. The current implementation is about trading space for time.

3. Deleting records does not release space: This is easy to understand. In order to avoid large-scale movement of data after deletion of records, the original record space is not deleted and can only be marked as "deleted", which can be reused in the future.

4. You can run db.repairDatabase() regularly to organize records, but this process will be slow.

③MongoDB does not have as mature maintenance tools as MySQL, which is worth noting for both development and IT operations.

Due to restrictions on uploading attachments and text, sometimes some pictures and text may not be displayed. For details, please see: http://mp.weixin.qq.com/s?__biz=MzI5ODI3NzY2MA==&mid=100000725&idx=3&sn=1e1354fe3a774b01f3d4301f82735024#rd
Everyone is welcome to communicate.
Scan the QR code below to get more and more beautiful articles! (Scan the QR code to follow for unexpected surprises!!)

Advantages and disadvantages of mongodb compared with mysql Follow our WeChat subscription account (uniguytech100) and service account (uniguytech) to get more and more exquisite articles!
You are also welcome to join [Everyone Technology Network Discussion QQ Group], group number: 256175955, please note your personal introduction! Let’s talk about it together!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment