Basic knowledge of MongoDB
MongoDB is a non-relational database. Compared with traditional relational databases, its data structure is more flexible, more scalable, supports more data types and data operations, and also has better performance and scalability. sex. Understanding the basics of MongoDB can help us better design and optimize data models, improve application performance and scalability, and also help us understand some concepts and technologies in back-end development.
1- Introduction to NoSQL database
NoSQL refers to non-relational databases, corresponding to traditional relational databases. In NoSQL databases, data is stored in the form of key-value pairs, documents, column families, or graphs, rather than in the form of traditional two-dimensional tables.
Compared with traditional relational databases, NoSQL databases have better scalability, better performance and higher flexibility. Common NoSQL databases include MongoDB, Cassandra, Redis, and Couchbase. I found a picture on Baidu, which vividly shows the difference between the two databases (if there is any infringement, please contact me to delete)
A traditional database can be compared to a library. Each book has a clear number, classification, location and other information, which is cumbersome to retrieve and manage. The NoSQL database can be compared to a scattered study room. Books are not clearly numbered and classified, but they can be quickly retrieved and managed as needed, making it more flexible and convenient to use.
In other words, a traditional database is like a structured questionnaire, which needs to be filled in and queried in a prescribed format, while a NoSQL database is like a free-form notebook, which is more suitable for processing unstructured and large-scale data.
2-MongoDB concepts and features
MongoDB is a document-oriented database that stores data in JSON format. It has a rich query language and high-performance read and write capabilities. It also supports functions such as automatic data fragmentation and multi-copy deployment, which can easily handle large-scale data processing. . Has the following characteristics
2.1-Non-relational database
MongoDB is a non-relational database, also known as NoSQL database. Unlike traditional relational databases, MongoDB documents can have different structures, and fields can be nested and extended, making data modeling more flexible and free.
2-2 document storage
MongoDB data is stored in the form of documents, each document is a collection of key-value pairs, similar to the JSON format, can nest sub-documents, and supports array-type fields. MongoDB supports a variety of data types, including text, numbers, dates, arrays, objects, and more.
2.3-Distributed storage
MongoDB supports distributed storage, and can achieve high availability and scalability through horizontal expansion. Through data sharding, data is scattered and stored on multiple nodes, thereby improving data availability and performance.
2.4-High Performance
MongoDB has the characteristics of high performance, can support fast read and write operations, and supports complex query statements and indexes, and provides a variety of query methods and sorting methods.
2.5-Scalability
MongoDB’s architectural design can well support horizontal expansion, and can expand data storage and processing capabilities by adding nodes, so as to adapt to the growing data size and access volume.
2.6-Data Security
MongoDB provides security measures such as security authentication mechanism and data encryption to ensure the security and integrity of data.
3-MongoDB installation and configuration
My technology stack is js, let’s use win computer and node.js as an example
3.1-Download and install MongoDB
Download the installation package corresponding to the operating system on the MongoDB official website, and install it in a fool-like manner according to the default configuration.
https://www.mongodb.com/docs/manual/
3.2-Configure environment variables
Add the MongoDB installation path to the environment variable of the operating system
C:\Program Files\MongoDB\Server\5.0\bin.
3.3-Create data storage directory
Create a data directory, and create two empty folders db and logs under this directory to store database files and log files.
D:\MongoDB\data\db D:\MongoDB\data\logs
3.4-Start MongoDB service
Enter the command mongod in a terminal or command line window
mongod
Start the MongoDB service. If the startup fails, you need to check whether other programs occupy the default port number (27017) of MongoDB. You can specify the port number in the startup command
mongod --port <port number>.
3.5-Connect to MongoDB
If the connection fails, you need to check whether the connection parameters are correct, such as whether the correct IP address and port number are specified
mongo --host <host name> --port <port number>
3.6-node.js case
const MongoClient = require('mongodb').MongoClient; const uri = "mongodb://localhost:27017/mydb"; MongoClient.connect(uri, function(err, db) {<!-- --> if (err) throw err; const dbo = db.db("mydb"); dbo.collection("customers").findOne({<!-- -->}, function(err, result) {<!-- --> if (err) throw err; console. log(result); db. close(); }); });
4-MongoDB basic operation and command line operation
After successfully connecting to MongoDB, we can start basic operations, that is, adding, deleting, modifying and checking. Here are some commonly used command-line operations:
4.1-Insert data
Insert a document into the current collection, document is a JSON object, representing the data to be inserted
db. collection. insert(document)
Using insertOne is to insert a piece of data, if you need to insert multiple documents, use the insertMany method
db.collection('users').insertOne({name: 'John', age: 30}); db.collection('users').insertMany([{name: 'Jane', age: 25}, {name: 'Jack', age: 35}]);
4.2-Query data
Use the find method to query data, and you can filter out qualified data by specifying conditions
db.collection.find(query, projection):
Query the documents in the current collection, query is the query condition, and projection is an optional parameter, indicating the field to be returned. Both query conditions and return fields can be set using MongoDB’s query operators.
db.collection('users').find({age: {$gt: 25}});
in,
g
t
means greater than,
gt means greater than,
gt means greater than, lt means less than, $eq means equal to and so on.
4.3-Update data
db. collection. update(query, update, options)
Update the eligible documents in the current collection, query is the query condition, update is the field to be updated, and options is an optional parameter, which is used to set some attributes of the update operation. You can also use updateOne or updateMany methods to update data
db.collection('users').updateOne({name: 'John'}, {$set: {age: 40}}); db.collection('users').updateMany({age: {$lt: 30}}, {$set: {age: 30}});
4.4-Delete data
db.collection.delete(query)
Delete documents that meet the conditions in the current collection. query is the query condition. Similarly, deleteOne or deleteMany methods can also be used to delete data
db.collection('users').deleteOne({name: 'John'}); db.collection('users').deleteMany({age: {$lt: 30}});
4.5 – Other commands
// delete the current database db. dropDatabase() // Create a collection (similar to a table in a traditional database), name is the name of the collection, and options are optional parameters for setting some properties of the collection db. createCollection(name, options) // delete the current collection db. collection. drop() // Use the aggregation pipeline to aggregate the current collection. An aggregation pipeline is a series of aggregation stages, each of which applies a transformation to the input documents and then passes the transformed results to the next stage. db.collection.aggregate(pipeline) // Create an index for the documents in the current collection, keys are the fields that need to be indexed, and options are optional parameters for setting some properties of the index. Indexes can improve query performance. db. collection. ensureIndex(keys, options)
These command line operations are just the tip of the iceberg of MongoDB, and there are many advanced usages and commands that can be learned in depth.