Routine Maintenance and Management of MongoDB

Source: Internet
Author: User
Tags mongodb server web database mongodump mongorestore
This section describes the routine maintenance management tools for routine operation and maintenance of MongoDB, including using configuration files, setting access control, Shell interaction, system monitoring and management, after daily database backup and recovery start and stop MongoDB start, you can access the Web database through the database IP address and port number. The configuration file is started by flushing the configuration file.

This section describes the routine maintenance management tools for routine operation and maintenance of MongoDB, including using configuration files, setting access control, Shell interaction, system monitoring and management, after daily database backup and recovery start and stop MongoDB start, you can access the Web database through the database IP address and port number. The configuration file is started by flushing the configuration file.

This section describes the routine maintenance management tools for routine operation and maintenance of MongoDB, including using configuration files, setting access control, Shell interaction, system monitoring and management, after daily database backup and recovery start and stop MongoDB start, you can access the Web database through the database IP address and port number. Configuration File
Start the database instance by flushing the configuration file, and create and edit mongodb. config in the bin folder (the name is optional)
Add dbpath =/data/db/to the example/
Add the -- f parameter at startup and point to the configuration file. Why do we use Daemon to start Daemon? When we close the session port of the Database Service, the MongoDB service is terminated, which is very insecure. Start the daemon.
Add the -- fork parameter. Here, you must specify the log storage file, that is, the -- logpath parameter for startup.
Example:
./mongod.exe --dbpath = D:\MongoDB  --logpath = D:\MongoDB\log\mongodb50.log   --fork
Common mongod parameter description dbpath: data file storage path
Logpath: the log file to store.
Bind_ip: the IP address bound to the external service. It is generally empty and open to all IP addresses.
Port: fork to start the service in the form of Daemon, and the web management end adds 1000
Journal: enables the log function and saves operation logs to reduce the recovery time for standalone faults,
Config: when there are many parameter rows, use this parameter to set the location of the parameter file to close the database and directly use Control + C to interrupt the database.
In the connect connection status, you can switch to the admin data, and then directly send the db. shutdownServer () command in the database to terminate the MongoDB instance.
Run Kill-2 PID or Kill-15 PID on Unix to terminate the process.
 ps aux|grep mongod    kill -2 (yourPID)    ps aux|grep mongod

Note: The kill-9 PID cannot be used.Kill the process, which may cause MongoDB database corruption.

Bind_ip
// MongoDB can only allow access from a specific IP address. You only need to add the bind_ip parameter at startup, as shown below:
[Root @ mongodb01/home/mongo/mongodb-2.0.2/bin] $./mongod -- bind_ip 192.168.1.61
Set listening port -- port
// Modify the server listening port to 27018:
[Root @ mongodb01/home/mongo/mongodb-2.0.2/bin] $./mongod -- bind_ip 192.168.1.61 -- port 27018
// (Error Code) if no port is specified during client access, the system will connect to the default port 27017. In this case, an error is reported. The Code is as follows:
[Root @ mongodb01/home/mongo/mongodb-2.0.2/bin] $./mongo 192.168.1.50
MongoDB shell version: 2.0.2
Connecting to: 192.168.1.61/test
Sun Apr 14 21:45:26 Error: couldn't connect to server 192.168.1.50 shell/mongo. js: 81 exception: connect failed
Log On with the username and password -- use the -- auth parameter at startup
// Enable the login verification module of the system. You only need to specify the auth parameter at startup. The Code is as follows:
[Root @ mongodb01/home/mongo/mongodb-2.0.2/bin] $./mongod -- auth start Authentication

By default, an admin database is available. users saved in admin. system. users have higher permissions than those set in other databases. Add admin. system. with the permissions of users, the client can connect to the database without any authentication and perform any operations on the database, only in admin. system. if a user is added to users, the -- auth parameter is enabled.

1. Create a system root user

>db.addUser("root","123456")>db.auth("root","123456")

2. Create a read-only user

>db.addUser("user_reader","1234567",true)

To add read-only permissions, you only need to add the third parameter, true.

Use command line

MongoDB can not only interact with each other, but also execute specified JavaScript files, execute specified command fragments, and use Linux Shell.

1. Run the specified statement using the eval Parameter

Query the number of records in the t1 set of the test database:

Db. t1.find ()

{"_ Id": ObjectId ("4f8ac746b2764d3c3e2cafbb"), "num": 1}

{"_ Id": ObjectId ("4f8ac74cb2764d3c3e2cafbc"), "num": 2}

{"_ Id": ObjectId ("4f8ac74eb2764d3c3e2cafbd"), "num": 3}

{"_ Id": ObjectId ("4f8ac751b2764d3c3e2cafbe"), "num": 4}

{"_ Id": ObjectId ("4f8ac755b2764d3c3e2cafbf"), "num": 5}

Db. t1.count ()

5

Use the -- eval parameter to directly execute the number in the ti set.

$./mongo.exe  --eval  "printjson(db.t1.count())"MongoDB shell version: 2.0.2connecting to: test5

2. Use the js file to execute the File Content

$cat t1_count.jsvar count = db.t1.count();printjson('count of t1 is: '+count);

Shown:

 $./mongo t1_count.jsMongoDB shell version: 2.0.2connecting to: test"count of t1 is: 5"

Tips:Use the -- quiet parameter to shield some login information to make the results clearer.

$ ./mongo --quiet t1_count.js"count of t1 is: 5"
Process Management View active processes
> Db. currentOp ()> db. $ cmd. sys. inprog. findOne () // $ cmd call an external Function

Shown as follows:

> db.currentOp(){        "inprog" : [                {                        "opid" : 630385,                          "active" : true,                        "lockType" : "read",                        "waitingForLock" : false,                        "secs_running" : 0,                        "op" : "query",                        "ns" : "test",                        "query" : {                                "count" : "t1",                                "query" : {                                },                                "fields" : {                                }                        },                        "client" : "127.0.0.1:51324",                        "desc" : "conn",                        "threadId" : "0x7f066087f710",                        "connectionId" : 7,                        "numYields" : 0                }        ]}>

Code explanation:

Opid: indicates the operating process number.
Op: Operation Type (query, update, etc)
Ns: namespace, operation object
Query: displays the specific operation content.
LockType: lock type, specifying whether to write or read the lock to terminate the process
> db.killOp(630385){ "info" : "attempting to kill op" }

Let's take a look:

> db.currentOp(){ "inprog" : [ ] }>
Monitor System Status and Performance

The serverStatus command can be used to obtain the statistics of the running MongoDB server. Next, run the command to view the statistics of the MongoDB server (Keys of different platforms or versions may vary ), the Code is as follows:

> db.runCommand({"serverStatus":1}){        "host" : "lindenpatservermongodb01",        "version" : "2.0.2",        "process" : "mongod",        "uptime" : 6003,        "uptimeEstimate" : 5926,        "localTime" : ISODate("2012-04-15T11:02:21.795Z"),        "globalLock" : {                "totalTime" : 6002811172,                "lockTime" : 24867,                "ratio" : 0.000004142559092311891,                "currentQueue" : {                        "total" : 0,                        "readers" : 0,                        "writers" : 0                },                "activeClients" : {                        "total" : 0,                        "readers" : 0,                        "writers" : 0                }        },        "mem" : {                "bits" : 64,                "resident" : 52,                "virtual" : 1175,                "supported" : true,                "mapped" : 160,                "mappedWithJournal" : 320        },        "connections" : {                "current" : 1,                "available" : 818        },        "extra_info" : {                "note" : "fields vary by platform",                "heap_usage_bytes" : 341808,                "page_faults" : 14        },        "indexCounters" : {                "btree" : {                        "accesses" : 1,                        "hits" : 1,                        "misses" : 0,                        "resets" : 0,                        "missRatio" : 0                }        },        "backgroundFlushing" : {                "flushes" : 100,                "total_ms" : 13,                "average_ms" : 0.13,                "last_ms" : 1,                "last_finished" : ISODate("2012-04-15T11:02:19.010Z")        },        "cursors" : {                "totalOpen" : 0,                "clientCursors_size" : 0,                "timedOut" : 0        },        "network" : {                "bytesIn" : 1729666458,                "bytesOut" : 1349989344,                "numRequests" : 21093517        },        "opcounters" : {                "insert" : 5,                "query" : 8,                "update" : 0,                "delete" : 0,                "getmore" : 0,                "command" : 21093463        },        "asserts" : {                "regular" : 0,                "warning" : 0,                "msg" : 0,                "user" : 0,                "rollovers" : 0        },        "writeBacksQueued" : false,        "dur" : {                "commits" : 30,                "journaledMB" : 0,                "writeToDataFilesMB" : 0,                "compression" : 0,                "commitsInWriteLock" : 0,                "earlyCommits" : 0,                "timeMs" : {                        "dt" : 3073,                        "prepLogBuffer" : 0,                        "writeToJournal" : 0,                        "writeToDataFiles" : 0,                        "remapPrivateView" : 0                }        },        "ok" : 1}>
Data Export and Import MongoexportAnd Mongoinport

Use Export export to export data

First look at the data:

> db.t1.find(){ "_id" : ObjectId("4f8ac746b2764d3c3e2cafbb"), "num" : 1 }{ "_id" : ObjectId("4f8ac74cb2764d3c3e2cafbc"), "num" : 2 }{ "_id" : ObjectId("4f8ac74eb2764d3c3e2cafbd"), "num" : 3 }{ "_id" : ObjectId("4f8ac751b2764d3c3e2cafbe"), "num" : 4 }{ "_id" : ObjectId("4f8ac755b2764d3c3e2cafbf"), "num" : 5 }>
Code:
./mongoexport.exe -d test -c t1 -o t1.datconnected to: 127.0.0.1exported 5 records[root@mongodb01 /home/mongo/mongodb-2.0.2/bin]$ lsbsondump  mongodump    mongoimport   mongosniff  t1_count.jsmongo     mongoexport  mongorestore  mongostat   t1.datmongod    mongofiles   mongos        mongotop    testfiles.txt[root@mongodb01 /home/mongo/mongodb-2.0.2/bin]$ cat t1.dat{ "_id" : ObjectId("4f8ac746b2764d3c3e2cafbb"), "num" : 1 }{ "_id" : ObjectId("4f8ac74cb2764d3c3e2cafbc"), "num" : 2 }{ "_id" : ObjectId("4f8ac74eb2764d3c3e2cafbd"), "num" : 3 }{ "_id" : ObjectId("4f8ac751b2764d3c3e2cafbe"), "num" : 4 }{ "_id" : ObjectId("4f8ac755b2764d3c3e2cafbf"), "num" : 5 }

./Export export.exe-d test-c t1-o t1.datParameters

-D: indicates the database to be used.
-C: indicates the export set. Here is t1.
-O: name of the exported data. By default, relative paths and absolute paths are used for the data names.

The exported data is in JSON format or csv format;

The exported CSV code file is as follows:

./mongoexport -d test -c t1 -csv -f num -o t1.dat
-Csv: Specifies the CSV format to be exported.
-F: Specifies the examples to be exported.

Data Import into import

Delete ti:

> db.t1.drop()true> show collectionssystem.indexessystem.users>

Import the data again. Here the csv data is imported:

./mongoimport -d test -c t1 --type csv --headerline -file /home/t1.datconnected to: 127.0.0.1

Check whether the imported data is the same:

> db.t1.find(){ "_id" : ObjectId("4f8ac746b2764d3c3e2cafbb"), "num" : 1 }{ "_id" : ObjectId("4f8ac74cb2764d3c3e2cafbc"), "num" : 2 }{ "_id" : ObjectId("4f8ac74eb2764d3c3e2cafbd"), "num" : 3 }{ "_id" : ObjectId("4f8ac751b2764d3c3e2cafbe"), "num" : 4 }{ "_id" : ObjectId("4f8ac755b2764d3c3e2cafbf"), "num" : 5 }>
-- Type csv: the data format imported is CSV. Why is it better to import CSV to major databases? JSON, as a lightweight data format, has some drawbacks.
-- File: Specifies the path of the imported file. data backup and recovery use data backup mongodump
./mongodump -d test -o /home/dump
-O: indicates the output backup path. If this option is not used, MongoDB automatically creates a dump folder and stores the backup file in it. Use mongorestore for data recovery

Mongorestore obtains mongodump output results and inserts the backup data into the running MongoDB.

./mongorestore -d test dump/*connected to: 127.0.0.1Thu Apr 19 18:16:12 dump/test/system.users.bsonThu Apr 19 18:16:12      going into namespace [test.system.users]2 objects foundThu Apr 19 18:16:12 dump/test/t1.bsonThu Apr 19 18:16:12      going into namespace [test.t1]5 objects foundThu Apr 19 18:16:12 dump/test/system.indexes.bsonThu Apr 19 18:16:12      going into namespace [test.system.indexes]Thu Apr 19 18:16:12 { key: { _id: 1 }, ns: "test.system.users", name: "_id_" }Thu Apr 19 18:16:13 { key: { _id: 1 }, ns: "test.t1", name: "_id_" }2 objects found

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.