MongoDB from the site to the Buddha (introduction, installation, addition, deletion, modification and investigation)

The author's public account bigsaihas been included in the carriage return class . If you are helpful, please don't hesitate to give a thumbs up and support!

Course Guide

Hello everyone. I’m bigsai. We have all studied databases, but you may be more familiar with relational (type) databases such as MySQL, SQL SERVER, ORACLE, etc. You may be unfamiliar with non-relational (type) databases, because most entry-level projects or learning The requirements for the use of non-relational databases are not high, so you will know less. But when it comes to performance and functionality, the performance of non-relational databases is very impressive! Today we will introduce, learn and use one of the non-relational databases-MongoDB database!

This article will introduce MongoDB related content and the installation of MongoDB, but your computer needs to have Studio 3T (download link https://studio3t.com/ ) to connect and manage MongoDB.

It doesn’t matter if you haven’t seen it before or if you haven’t used it, this course will be taught!

Through this article, you can master the following:

  • Meet MongoDB
  • Implement MongoDB's addition, deletion, modification, and check

Introduction to MongoDB

Before introducing MongoDB, ask a question, do you know what MongoDB is?

You might say that it is a non-relational database, and more probably you don’t know much about it. It doesn’t matter, let’s go through it layer by layer.

in

1.1 Non-relational database

NoSQL (Not Only SQL), literally translated, is not only a database, but also a non-relational database. With the rise of Internet web2.0 websites, traditional relational databases have been unable to handle web2.0 websites, especially the ultra-large-scale and high-concurrency web2.0 pure dynamic websites, and there have been many insurmountable problems. Non-relational databases have developed rapidly due to their own characteristics. The creation of non-relational databases is to solve the challenges brought by multiple data types in large-scale data collections, especially the problems of big data applications.

Non-relational databases are divided into several types:

Key-Value storage database : This type of database uses a hash table. This model is very similar to the use of HashMap in Java. It is relatively simple to use and easy to deploy, but if only part of the data is queried or updated The efficiency is not very high. Such non-relational databases include Redis and Oracle BDB.

Column storage database : This part of the database is usually used to deal with the massive data of distributed storage. The keys still exist, but their characteristic is that they point to multiple columns. These columns are arranged by the column family. Such as: HBase, Riak, etc.

Document database : It is similar to key-value storage. This type of data is stored in a specific format, such as JSON. The document database can be regarded as an upgraded version of the key-value database, allowing nesting of key-values, and is more efficient than traditional key-value databases when processing complex data such as web pages. And MongoDB is an efficient document database.

Graph database : Graph database is a non-relational database. It uses graph theory to store the relationship information between entities and can be well extended to other servers.

Although there are so many differences between non-relational databases (NoSQL), they still have many common features:

Easy to expand : There are many types of NoSQL databases, but they all have one common feature: removing the relational characteristics of relational databases. There is no relationship between the data, all depends on the designer's design. This is very easy to expand, and intangible also brings scalability at the architectural level.

Large amount of data, high performance : NoSQL databases have very high read and write performance, especially under large amounts of data. This is due to its non-relational nature, simple database structure, and the ability to quickly find and locate data.

1.2 Features of MongoDB

After talking about what NoSQL is, let's take a look at what MongoDB is. What is MongoDB?

MongoDB is a database based on distributed file storage. Written by C++ language. Designed to provide scalable high-performance data storage solutions for web applications. MongoDB is a product between relational and non-relational databases. It is the most versatile and most like relational database among non-relational databases. The data structure it supports is very loose, and it is a BSON format similar to JSON, so it can store more complex data types. The biggest feature of MongoDB is that the query language it supports is very powerful. Its syntax is a bit similar to an object-oriented query language. It can almost achieve most of the functions similar to single-table queries in relational databases, and it also supports indexing of data.

And MongoDB has become more and more popular recently. As a document-based non-relational database, it can be used in more and more scenarios. By studying the official MongoDB documentation ( https://docs.mongodb.com/manual/ ), we conclude that MongoDB has the following characteristics:

  • Easy to use: MongoDB stores data in flexible, JSON- like documents, and the document model is mapped to objects in the application code, making the data easy to use.
  • High performance: MongoDB provides high performance data durability. In particular, support for embedded data models reduces I/O activity on the database system.
    The index supports faster queries and can contain keys from embedded documents and arrays.
  • Rich query language: MongoDB supports a rich query language to support read-write operations (CRUD) and: data summary text search and geospatial query.
  • High availability: MongoDB's replication tool (called replica set) provides: automatic failover, data redundancy.
  • Horizontal scalability: MongoDB provides horizontal scalability as part of its core function: sharding distributes data across a set of computer clusters.
    Starting from 3.4, MongoDB supports the creation of data areas based on shard keys. In a balanced cluster, MongoDB only directs reads and writes covered by the region to those shards in the region.
  • Supports multiple storage engines MongoDB supports multiple storage engines:
    WiredTiger storage engine (including support for encryption at rest) in-
    memory storage engine.

In summary, the high-performance MongoDB that a NoSQL should have is readily available, and it is a non-relational document database that is easy to use and good at storing. But MongoDB is not 100% perfect. It also has certain flaws such as not supporting transactions, taking up a lot of memory, deleting records without releasing space, and not having mature maintenance tools.

1.3 Application Scenarios of MongoDB

With the above features, MongoDB has many good points in the increasingly complex web field .

  • Insert, update, and delete real-time data on the website.
  • Large-scale but high-cost data (large size, low-value data)
  • Object or JSON text storage
  • Data that does not require frequent table calculations and does not require high transaction requirements.
  • Some application layer caching

The specific application scenarios are:

  • In social scenarios, MongoDB is used to store user information and the user's Moments information, and functions such as nearby people and places are realized through geographic indexing.
  • In the game scene, MongoDB is used to store game user information, and the user's equipment, points, etc. are directly stored in the form of embedded documents, which is convenient for query, efficient storage and access.
  • In logistics scenarios, MongoDB is used to store order information, and the order status will be constantly updated during the delivery process. It is stored in the form of an embedded array of MongoDB, and all changes to the order can be read out with one query.
  • In the Internet of Things scenario, MongoDB is used to store all connected smart device information and log information reported by the device, and conduct multi-dimensional analysis of this information.
  • Live video, use MongoDB to store user information, like interactive information, etc.

These scenarios have the characteristics of large data volume, frequent write operations, low data value, and low transactional requirements.

Many people regard MongoDB as big data for the poor. You can understand it as a non-relational database that is highly efficient but more suitable for direct operation. Most data that does not require "brain" can be stored in MongoDB. For example, many people store crawler data in MongoDB. , Or perhaps put some information records of the website in MongoDB. It doesn't matter if the data is larger, but it is not recommended that the query needs to be too complicated and should not be related to ACID transactions.

MongoDB is like a strong man in the family . He does all the dirty work, he is not too tired, he is as powerful as an ox, and his steps are like flying. It’s best to use him for these physical tasks (fast speed, good performance, large files storage), but he has some shortcomings in that he may eat seven or eight bowls of dry rice every time he eats, two or three catties of meat (occupies a lot of memory), and he has to thread needles and settle accounts at home He can't remember these things, he has to do this with his wife (Relational Database)

in

The second level MongoDB installation and table structure

After you know what MongoDB is and what it can do, it's time to install and understand how to use it! This level takes you to install MongoDB and understand the table structure of MongoDB.

2.1 Installation of MongoDB

The installation of MongoDB is very simple, here is the installation based on windows. Go to MongoDB official website to download

in
Then open the downloaded file, all the way to next to the middle, check whether to choose compass according to your needs. Compass is a visual management tool for MongoDB. MongoDB has many visual management tools, so we don't check this content here .in

Choose Custom to customize the installation according to your needs:

in
You can customize the folder to location, or use its default:
in

Check the first "Connect to the network" below: In
in
this way, your MongoDB installation is complete, and then install the MongoDB visualization tool: studio3t ( https://studio3t.com/ ) After downloading and installing, open the direct connection
in

At this point, MongoDB is installed and has three databases: admin, config, and local by default. Some log configuration and other databases, don't care about it here.
in

2.2 MongoDB table structure

For a relational database, we may easily understand its hierarchy: database -> table -> record (row) -> column , while MongoDB corresponds to: database -> collection -> document -> field . Among them, collections can be analogous to tables in relational databases, and documents can be regarded as records.

SQL terms/concepts MongoDB terms/concepts explain
database database database
table collection Database table/collection
row document Data record line/document
column field Data field/domain
index index index
table joins Table connection, MongoDB does not support
primary key primary key Primary key, MongoDB automatically sets the _id field as the primary key

Documents : Documents are the basic unit of data in MongoDB, similar to JSON objects and rows in relational databases (but more complex than rows). It is a data structure composed of multiple data fields and value pairs. The value of a field can also be other documents or document arrays.

Collection : A collection is a set of documents, similar to a table in a relational database. The collection is modeless, and the documents in the collection can be of all kinds. Although there is no content restriction on the documents in a collection, we generally put the same types of documents in the same collection (to improve query efficiency).

Database : Multiple documents in MongoDB form a collection, and multiple collections form a database. A MongoDB instance can host multiple databases. They can be regarded as independent of each other, and each database has independent access control. On the disk, different data banks are placed in different files. The following system databases exist in MongoDB.

  • Admin database: a permissions database, if the user is added to the admin database when creating a user, the user will automatically inherit the permissions of all databases.
  • Local database: This database will never be replicated and can be used to store any collection of local single servers.
  • Config database: When MongoDB uses fragmentation mode, the config database is used internally to store fragmentation information.

in

You may find that there are Views and GridFS Buckets at the contract level. What are they?

Views: MongoDB views are queryable objects whose contents are defined by aggregation pipelines on other collections or views. MongoDB does not persist the contents of the view to disk. When the client queries the view, the content of the view will be calculated on demand. MongoDB does not support write operations to views. This is a bit similar to the MySQL view. It is a virtual table. You can use it to streamline some query steps and operations.

GridFS: GridFS is a specification for storing and retrieving files that exceed the BSON document size limit (16MB). GridFS does not store files in a single document, but divides the file into multiple parts or chunks, and stores each chunk as a separate document.

The third level of MongoDB additions, deletions, and changes

Before learning to use MongoDB, you must master the basic addition, deletion, and modification operations of MongoDB. Let's use the console or database management tools to operate MongoDB first, in preparation for later integration into the project. MongoDB has developed into different versions to this day. The api of MongoDB 3.2 and later versions has some changes and optimizations compared with the previous version of 3.2. The learning and introduction of official documents are based on the version 3.2 and later, so it is necessary to learn the api syntax of MongoDB Learn the latest grammar by referring to the official document to avoid confusion of knowledge caused by the over-old grammar.

Create a database
We use studio 3T to create a database and collection, the database is named mongo. If you do not create a database, inserting data into mongoDB will be inserted into the test database by default.
in

Then add a collection to the database, the collection is named student:
in

It can be found that the student collection has been successfully added:

Insert picture description here

MongoDB read operations include queries, and write operations include insert, update, and delete. All write operations in MongoDB are atomic operations at the single document level. You can specify query, update, and delete criteria or filters (query, update, delete Update conditions) to identify the documents to be queried, updated, or deleted. You can understand that the filter is a conditional where clause of a relational database query.

3.1 MongoDB insert

The insert operation is complete to insert a document into the collection. MongoDB provides the following methods to insert a document into the collection:

db.collection.insertOne() //New in version 3.2 插入一条文档(document)
db.collection.insertMany() //New in version 3.2 插入多条文档(document)
db.collection.insert()//老版本语法 

Among them, the collection needs to be changed to the name of the collection to be inserted during insertion, and the document to be inserted needs to be inserted into the corresponding collection, otherwise a collection will be created by default and then inserted. Here we insert a document into the student collection.

Before using the mongo database, execute the statement:, use mongoyou can directly operate the mongo database after execution.
The syntax of MongoDB's insert is as follows. It is more recommended to use insertOne and insertMany to insert one and multiple documents respectively:

Insert a single document into the student collection and execute the following statement:

db.student.insertOne({
    
    "name": "bigsai","age":"22"})

in
Insert multiple documents (document), execute the following statement:

db.student.insertMany([{
    
    "name": "bigsai2","age":"22"},{
    
    "name": "bigsai3","age":"22"}])

in

Open the student collection, you will find that the above document (document) was successfully inserted.

in

3.2 MongoDB query

The query operation is complete to query documents from the collection. MongoDB provides the following methods to insert documents into the collection:

db.collection.find()//查询文档,在括号内添加各种条件

You can specify query filters or conditions to identify documents to be returned. Of course, MongoDB also supports a variety of conditional queries, and it is very simple to use. You need to check the official documents ( https://docs.mongodb.com/manual/tutorial/query-documents/ ), here to query the data field age in the student collection Take the document of 22 as an example, show it:

//db.student.find()//查询所有类似select * from student
db.student.find({
   
   "age":"22"})

You can see that the query results are as follows, and all documents whose data field age is 22 have been queried.
in

3.3 MongoDB update

The update operation is complete to update (modify) the document from the collection. MongoDB provides the following methods to update the collection document:

db.collection.updateOne() //3.2版中的新功能 更新一条文档记录
db.collection.updateMany() //3.2版中的新功能 更新多条文档记录
db.collection.replaceOne() //3.2版中的新功能 替换集合中的一个文档

In MongoDB, the update operation is only for a single collection (the corresponding collection in db.collection). All write operations (including updates) in MongoDB are atomic operations at the single document level. You can specify update criteria or filters (update conditions) to identify the documents to be updated. These filters are consistent with the filter usage used in the query. Of course MongoDB has an update() method but it has been deprecated.

We update all documents in the student collection whose data field age is 22 to bigsai22:

db.student.updateOne(
     {
    
    "age":"22"},//条件
     {
    
    $set:{
    
    "name":"bigsai2"}}//修改的值
 )

Where {"age":"22"} is the query condition, that is, to find the first document whose data field age is 22, and {$set:{}} is used to modify the value of the corresponding data field of the document. The successful execution of updateOne() will only update the first matching document.

in

At this point, if you want to change bigsai2the data field age of the two documents whose data field name is to 18, then execute the following statement:

db.student.updateMany(
     {
    
    "name":"bigsai2"},
     {
    
    $set:{
    
    "age":"18"}}
 )

Refreshing the results will find that the document has been successfully updated. This statement is similar in SQLupdate student set age=18 where name=bigsai2
in

3.4 MongoDB delete

The delete operation is complete to delete documents from the collection. MongoDB provides the following methods to delete documents in the collection:

db.collection.deleteOne() //3.2版中的新功能 删除一条记录
db.collection.deleteMany() //3.2版中的新功能 删除多条记录

In MongoDB, the delete operation is only for a single collection (the corresponding collection in db.collection). All write operations (including deletion) in MongoDB are atomic operations at the level of a single document. You can specify criteria or filters to identify documents to be deleted. The usage of these filters is consistent with the filters used in query and update.

The conditions for delete and update operations are similar here. If you use the deleteOne() statement, the first matching document will be deleted, while using deleteMany() will delete all documents that meet the conditions. If we delete all documents whose data field name is bigsai2, we can do this:

db.student.deleteMany(
     {
    
    "name":"bigsai2"}//条件
 )

It can be found that the document was successfully deleted:
in

Course summary

At this point, the introduction of MongoDB is over. I think you must be able to know the ins and outs of MongoDB.

Recalling the content of this article, first, introduce the characteristics and scenarios of MongoDB, a non-relational database, from a macro perspective; then introduce the installation process of MongoDB and learn the table structure of MongoDB, so that you have a more detailed understanding of the rules of MongoDB Finally, teach you how to use statements to add, delete, modify and check MongoDB, so that you can operate MongoDB initially.

Of course, this article just takes you to get started with MongoDB and talks about some more basic content. If you need to learn to use MongoDB in depth, you need to learn more from the official website documents and other learning resources!

MongoDB is currently a very popular document-based non-relational database, and its applications are becoming more and more. Hope you can use MongoDB in the programming language as soon as possible after you understand MongoDB, and really use MongoDB in your project!

The code word is not easy, welcome to follow the author's public account to support a wave:, bigsailook forward to your attention and willing to share more content. Reply to bigsaiget a copy of selected pdf information.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40693171/article/details/108040117