MongoDB learning outline

MongoDB is an open source NoSQL database based on distributed file storage, mainly used for large-scale document storage. Here are some core concepts, commands and their interpretations that you must understand:

1. Databases, Collections and Documents

  • Database : The top-level organizational unit of MongoDB. One MongoDB instance can host multiple databases.
  • Collection : An organizational unit located within a database, similar to a table in a relational database, but without a fixed structure.
  • Document : A data record in JSON format, similar to rows in a relational database.
# 创建/切换数据库
use mydb

# 在当前数据库中创建集合
db.createCollection("mycollection")

# 向集合中插入文档
db.mycollection.insert({
    
    name: "Alice", age: 25, address: "123 Street"})

2. CRUD operations

  • Create : Create a document.
  • Read : Read the document.
  • Update : Update the document.
  • Delete : Delete the document.
# 插入文档
db.mycollection.insert({
    
    name: "Bob", age: 30})

# 查询文档
db.mycollection.find({
    
    age: {
    
    $gt: 25}})

# 更新文档
db.mycollection.update({
    
    name: "Alice"}, {
    
    $set: {
    
    age: 26}})

# 删除文档
db.mycollection.remove({
    
    name: "Bob"})

3.Index _

Indexes are used to improve database query performance. In MongoDB, you can create an index for one or more fields in a collection.

# 为name字段创建索引
db.mycollection.createIndex({
    
    name: 1})

4. Aggregation

MongoDB provides a powerful aggregation framework for various forms of data processing, such as grouping, filtering, sorting, etc.

# 按age字段分组,并计算每个年龄的人数
db.mycollection.aggregate([{
    
     $group: {
    
    _id: "$age", count: {
    
    $sum: 1}}}])

5. Backup and recovery

Regular backup is an important means to maintain database security. MongoDB provides mongodumpand mongorestoretools for backup and recovery.

# 备份数据库
mongodump --db mydb --out /path/to/backup

# 恢复数据库
mongorestore --db mydb /path/to/backup/mydb

6. Security

In a production environment, MongoDB needs to be properly configured for security, including network isolation, authentication and authorization, etc.

# 创建管理员用户
use admin
db.createUser({
    
    user: "admin", pwd: "adminpassword", roles: ["root"]})

# 启用认证
# 编辑mongod.conf,加入 security: authorization: enabled
# 重启MongoDB服务

These are the basic concepts and operations of MongoDB, but MongoDB also has many advanced features and optimization techniques, such as:

1. Sharding

Sharding is a method used in MongoDB to handle large-scale data sets. By distributing data across multiple servers, horizontal scalability can be achieved.

Set up sharding:

# 启动配置服务器 (configsvr)
mongod --configsvr --dbpath /path/to/configdb --port 27019

# 启动分片服务器 (shardsvr)
mongod --shardsvr --dbpath /path/to/sharddb --port 27020

# 启动mongos
mongos --configdb configsvr:27019

Add shards:

# 连接mongos
mongo --host mongos-hostname --port 27017

# 添加分片
sh.addShard("shardsvr:27020")

2. Replica Set

Replication sets provide data redundancy and high availability by replicating data to multiple servers, automatically switching to a backup server in the event of a primary server failure.

Configure the replica set:

# 启动MongoDB实例,指定复制集名称
mongod --dbpath /path/to/db --replSet "rs0" --port 27017

# 初始化复制集
mongo --eval "rs.initiate()"

3. Transaction processing

MongoDB 4.0 and later supports multi-document ACID transactions, which makes it possible to make changes to multiple documents in a single transaction.

// 开启一个Session
let session = db.getMongo().startSession()

// 开启一个事务
session.startTransaction()

try {
    
    
    // 执行事务内的操作
    session.getDatabase("mydb").mycollection.insertOne({
    
     name: "Alice" })
    session.getDatabase("mydb").mycollection.updateOne({
    
     name: "Bob" }, {
    
     $set: {
    
     age: 30 } })

    // 提交事务
    session.commitTransaction()
} catch (error) {
    
    
    // 出现错误,回滚事务
    session.abortTransaction()
    throw error
} finally {
    
    
    // 结束Session
    session.endSession()
}

4.Performance tuning

  • Index optimization : Proper creation and use of indexes is the key to improving query performance.
  • Query Optimization : Use projections to reduce the amount of data returned and use $explainto analyze query plans.
  • Write optimization : Batch writing can improve write performance, and write concern level (write concern) can affect the durability and consistency of writes.

5.Data migration

Use mongodumpand mongorestoretools to achieve data backup and recovery, and can also be used for data migration.

6.Failure recovery

In the event of a server failure, MongoDB can automatically failover if a replication set is configured. Backups can be used to restore data in the event of data error or loss.

7. Monitoring and log analysis

Use MongoDB's own monitoring tools, such as mongostatand mongotop, and third-party monitoring tools, such as Prometheusand Grafana, to monitor database performance and resource usage. Analyze MongoDB logs regularly to identify potential issues and performance bottlenecks.

In actual applications, these technologies need to be flexibly selected and applied according to specific business needs and system environment.

Guess you like

Origin blog.csdn.net/m0_57021623/article/details/133253380