SoFunction
Updated on 2025-04-12

MongoDB deployment super detailed step records

1. MongoDB installation configuration

1. Download the installation package

# /try/download/community
wget /linux/mongodb-linux-x86_64-rhel70-7.0.

2. Decompression

tar fx mongodb-linux-x86_64-rhel70-7.0. -C /usr/local/

3. Create a soft link

ln -s /usr/local/mongodb-linux-x86_64-rhel70-7.0.14/ /usr/local/mongodb

4. Create data and log directories

mkdir /usr/local/mongodb/{data,logs}
touch /usr/local/mongodb/logs/

5. Set environment variables

vim /etc/profile
export MONGODB_HOME=/usr/local/mongodb
export PATH=$MONGODB_HOME/bin:$PATH

6. Effective environment variables

source /etc/profile

7. Modify the configuration file

vim /etc/
#Specify the database pathdbpath=/usr/local/mongodb/data
#Specify MongoDB log filelogpath=/usr/local/mongodb/logs/
# Write logs using appendlogappend=true
#Port Numberport=27017 
#Convenient to access external networkbind_ip=0.0.0.0
fork=true # Run MongoDB as a daemon and create a server process#auth=true #Enable user authentication#bind_ip=0.0.0.0 #Bind service IP, if 127.0.0.1 is bound, it can only be accessed by local machine. If it is not specified, all local IPs will be defaulted to be accessed by default.#replSet=single #Enable oplog log for master-slave replication

8. Start and shut down the service

# start upmongod -f /etc/
# closuremongod --shutdown -f /etc/

9. Verification

 ps -ef|grep mongodb
 netstat -ntlp|grep 27017

2. MongoDB Shell installation

1. Download the installation package

# Download link: /try/download/shellwget /compass/mongosh-2.3.

2. Decompression

tar fx mongosh-2.3.

3. Modify the command directory

cp mongosh-2.3.2-linux-x64/bin/mongosh /usr/local/bin/

4. Log in

# No certification requiredmongosh
# Need to be certifiedmongosh mongodb://192.168.9.25:27017/admin -u "admin" -p "abc123456"

3. Collection of common commands

1. Role operation

1) Administrator role

# Can only create logic libraries in adminreadAnyDatabase: Only create users inadminIn the logic library,Allows reading of any logical library
readWriteAnyDatabase: Only create users inadminIn the logic library,Allows reading and writing of any logical library
dbAdminAnyDatabase: Only create users inadminIn the logic library,Allows management of any logical library
userAdminAnyDatabase: Only create users inadminIn the logic library,Allows management of any logical library用户
clusterAdmin: Only create users inadminIn the logic library,Allow managementMongoDBCluster
root: Only create users inadminIn the logic library,Super Administrator,Have the highest authority

2) Ordinary characters

# Create on the specified logical libraryRead: Allows users to read the specified logical library
readWrite: Allows users to read and write specified logic libraries
dbAdmin: Can manage specified logical libraries
userAdmin: Users who can manage specified logical libraries

3) Create a role

# Create an administratoruse admin
({user:"admin",pwd:"abc123456",roles:[{role:"root",db:"admin"}]})
# Create a normal roleuse common
({user:"qyc",pwd:"abc123456",roles:[{role:"dbAdmin",db:"common"},{role:"readWrite",db:"common"}]})

4) Query role

# Query all().pretty()
show users
# Query the specified role('qyc')
({usersInfo:"qyc"})

5) Update roles

('qyc',{'roles':[{'role':'userAdmin','db':'common'},{'role':'read','db':'common'}]})

6) Modify the role password

("qyc", "123456")

7) Delete the role

('qyc')

8) Role Certification

('qyc','123456')

2. Database operations

1) View all libraries

show dbs

2) Switch library

# Switch to the specified library, it will be automatically created if it does not existuse common

3) View the current library

db

4) Delete the current library

()

3. Collection operations

1) Create a collection

("student")

2) View the collection

show collections

3) Rename the collection

("stu")

4) View the number of collection records

()

5) View the collection data space capacity

# ()
# View the total size of the collection (bytes in units)()
# View the statistics of the collection()

6) Delete the collection

()

4. Document operation

1) Insert document in collection

# Insert a single({name:"Scott",sex:"male",age:25,city:"Beijing"})
# Insert multiple lines, save will update if the primary key of save exists, and insert if it does not exist.([{name:"Scott3",sex:"male",age:22,city:"Beijing"},{name:"Scott2",sex:"male",age:22,city:"Beijing"}])
([{name:"Scott3",sex:"male",age:22,city:"Beijing"},{name:"Scott2",sex:"male",age:22,city:"Beijing"}])
([{name:"Scott3",sex:"male",age:22,city:"Beijing"},{name:"Scott2",sex:"male",age:22,city:"Beijing"}])

2) Update the document

# Modify a record({name:"Scott2"},{$set:{age:26,classno:"2-6"}})
# Modify multiple records({name:"Scott3"},{$set:{classno:"2-7"}})
# Add 2 to the age attribute({},{$inc:{age:2}})
# Add elements to array properties({name:"Scott"},{$push:{role:"Squad Leader"}})

3) Extract time from document primary key ID

ObjectId("66dac03ddf68fdd4c95796d4").getTimestamp()

4) Delete the document

# Delete fields in the document, {} means modifying all({name:"Scott"},{$unset:{classno:"2-6"}})
# Delete an element in the array({name:"Scott"},{$pull:{role:"Squad Leader"}})
# Delete all documents({})
# Delete the specified document({name:"Scott2"})

5) Simple query

expression illustrate
$lt Less than
$gt Greater than
$lte Less than or equal to
$gte Greater than or equal to
$in include
$nin Not included
$ne Not equal to
$all Match all
$not Reverse
$or or
$exists Contains fields
# Query all documents()
# Query the specified document and display the specified field. 1 is displayed, 0 is not displayed.({name:"Scott3",classno:"2-8"},{name:1,_id:0})
({age:{$gte:24}})
({name:/^S/})
# View single record({name:/3$/})
# Document nested query# {class:{type: 1, data: [1,2,3]}}
({:1})
({.1:2})
({:[1,2,3]})

6) Pagination query

# Take the first ten().limit(10)
# Get ten items starting from 21 items().skip(20).limit(10)

7) Document sorting

# Data sort (1 represents ascending order, -1 represents descending order)().sort({name:1})

8) Document reimbursement

# Return the specified data after deduplication, the format is an array("name")
# is the data sort after deduplication (-1 is positive order, 1 is reverse order)("name").sort(function(){return -1})
# Intercept the specified data in the array, (0,5) means intercepting from the first line to the sixth line, (5) means intercepting the sixth line to the last line("name").slice(0,5)

5. Indexing operation

1) Create an index

# 1 ascending order, -1 descending order, background means to create when idle({name:1})
({name:-1},{background:true,name:"index_name"})

2) Create a unique index

({sid:1},{background:true,unique:true})

3) View the index

()

4) Delete the index

()

4. Backup and Restore

1. Full library backup

mongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -o /data

2. Backup the logic library

# --dumpDbUsersAndRoles parameter can back up users affiliated with the logical librarymongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -o /data

3. Backup collection data

# --gzip compression backup, --oplog uses oplog for point-time snapshotsmongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -c student -o /data
# Export data from JSON or CSV format data, -f specifies the output field, -q specifies the query statementmongoexport --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -c student -f "_id,name,sex,age" -o 

4. Single library recovery

# --drop means to delete the collection in the database before importingmongorestore --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin --drop -d school /data/school

5. Collection recovery

# --gzip decompression Gzip compressed archive restore, --oplogReplay operation content, --oplogLimit and --oplogReplay can be used together, and can be restricted to the specified time point.mongorestore --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -c student /data/school/
# Import json datamongoimport --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -c student --file 

6. Incremental recovery

# Use oplog parameters to be fully prepared, you need to enable the replica setmongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin --oplog -o /data
# parse oplog file and find out the data of the last timebsondump /data/ > /data/
# Export incremental data, modify it to the time stamp of the most recent linemongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d local -c  -q '{ts:{$gt:Timestamp(1610789118,416)}}' -o /data/oplog
# Restore full preparationmongorestore --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin --oplogReplay /data
# Copy the incremental oplog to the backup directory, rename it to overwrite the originalcp  /data/
# Restore incremental oplogs and specify the time point to restoremongorestore --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin --oplogReplay --oplogLimit "1610789168:1" /data

Summarize

This is all about this article about the super detailed steps of MongoDB deployment. For more related MongoDB deployment content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!