Detailed MongoDB Management Command _mongodb

Source: Internet
Author: User
Tags auth create index findone mongodb server relational database table mongodump mongo shell mongorestore

MongoDB is a NoSQL database system: A database can contain multiple sets (Collection), each set corresponds to a table in a relational database, and each collection can store a set of records identified by the column, which is freely defined, very flexible, The collection of entities identified by a set of columns corresponds to the rows in the relational database table. The following are familiar with the basic management commands of MongoDB to understand the basic functionality and behavior of the DBMS provided by MongoDB.

MongoDB Command Help system

After the MongoDB is installed, the server process (Mongod) is started, and MongoDB management and monitoring can be achieved by MONGO the client command. Take a look at MongoDB's command Help system:

 root@dev:~# MONGO MongoDB Shell version:.. Connecting To:test > Help Db.help () Help in DB Methods Db.mycoll.help () Help on collection m Ethods rs.help () help in replica set methods help connect connecting to a DB help Help ADM In Administrative Help Misc misc Things to know help Mr MapReduce help SHO          W DBS Show database names show collections show collections at current database show users
     Show users in the current database show profiles show most recent system.profile entries with time >= ms Use <db_name> Set current database Db.foo.find () list objects in collection Foo db.foo.fi nd ({a:}) List objects in Foo where a = = It result is the last line evaluated;   Use to further iterate dbquery.shellbatchsize = X Set default number of items to display on shell exit          Quit the MONGO shell  

This is the top-most command list for MongoDB, which tells us some of the abstract areas of managing databases: Database Operations Help, collection operations help, and administrative help. If you want to know more detailed help commands for database operations, you can use DB.HELP () directly, as follows:

 Db.help () DB methods:db.addUser (username, password[, readonly=false]) Db.auth (username, password) db.cl Onedatabase (fromhost) db.commandhelp (name) returns the Help for the command Db.copydatabase (Fromdb, Todb, Fromho
     ST) Db.createcollection (name, {size: ..., capped: ..., max: ...}) Db.currentop () Displays the current operation in the DB Db.dropdatabase () Db.eval (func, args) run code Server-si  De db.getcollection (CNAME) Same as db[' cname '] or db.cname db.getcollectionnames () db.getlasterror ()-Just Returns the Err Msg string db.getlasterrorobj ()-Return to Full status object Db.getmongo () get the server Connec
     tion Object Db.getmongo (). Setslaveok () Allow this connection to read from the Nonmaster member of a replica pair Db.getname () Db.getpreverror () db.getprofilinglevel ()-Deprecated db.getprofilingstatus ()-Returns if PR
 Ofiling is on and slow threshold db.getreplicationinfo ()    DB.GETSIBLINGDB (name) get the DB in the same server as this one db.ismaster () check replica primary status D B.killop (Opid) kills the current operation in the DB Db.listcommands () lists all DB commands Db.printcollect Ionstats () Db.printreplicationinfo () Db.printslavereplicationinfo () db.printshardingstatus () Db.remove User (username) db.repairdatabase () Db.reseterror () Db.runcommand (cmdobj) run a database command. If Cmdobj is a string, turns it into {cmdobj:} db.serverstatus () db.setprofilinglevel (level,<slowms>) = Off =slow =all db.shutdownserver () db.stats () db.version (), current version of the server Db.getmongo ()  . Setslaveok () Allow queries on a replication slave server

The basic commands for managing and manipulating the database can be obtained from the above. If you want to get more, and the detailed usage of each command, you can use the Db.listcommands () query listed above.

Another comparison is to manipulate, manage, and monitor a collection of specified databases, which can be obtained by querying Db.mycoll.help ():

Db.mycoll.help () dbcollection help Db.mycoll.find (). Help ()-Show dbcursor help Db.mycoll.count () Db.myco Ll.datasize () db.mycoll.distinct (key)-eg. Db.mycoll.distinct (' x ') Db.mycoll.drop () Drop the collection Db.mycoll.dropIndex (name) Db.mycoll.dropInde Xes () Db.mycoll.ensureIndex (Keypattern[,options])-options are an object with these possible fields:name, unique, Dr Opdups Db.mycoll.reIndex () db.mycoll.find ([query],[fields])-query is a optional query filter.
                            Fields is optional the set of fields to return. e.g. Db.mycoll.find ({x:}, {name:, x:}) Db.mycoll.find (...). Count () Db.mycoll.find (...). Limit (n) db.mycoll.find (...). Skip (N) db.mycoll.find (...).
     Sort (...) Db.mycoll.findOne ([query]) db.mycoll.findAndModify ({update: ..., remove:bool [, query: {}, Sort: {}, ' new ': FAL
SE]}) Db.mycoll.getDB () Get DB object associated with collection db.mycoll.getIndexes ()     Db.mycoll.group ({key: ..., initial: ..., reduce: ...) [, cond: ...] }) Db.mycoll.mapReduce (Mapfunction, reducefunction, <optional params>) db.mycoll.remove (query) d
     B.mycoll.renamecollection (NewName, <dropTarget>) renames the collection. Db.mycoll.runCommand (name, <options>) runs a DB command with the given name where the "the" is the Collecti On name Db.mycoll.save (obj) db.mycoll.stats () db.mycoll.storageSize ()-Includes free spaces allocated to th Is collection db.mycoll.totalIndexSize ()-size in bytes of all Indexes db.mycoll.totalSize ()-Storage Allo  cated for all data and indexes db.mycoll.update (query, object[, Upsert_bool, Multi_bool]) db.mycoll.validate ()-  Slow Db.mycoll.getShardVersion ()-only for use with sharding

Relevant commands for database and collection management are the most basic and commonly used, such as collection queries, indexing operations, and so on.

Basic commands and examples

The following examples illustrate some of the most common commands:

(i) Basic orders

1, show DBS

Displays the database on the current database server

2. Use Pagedb

Switches to the context of the specified database Pagedb, where you can manage the Pagedb database and the collections therein

3, Show collections

Display all collections in the Database (collection)

4, Db.serverstatus ()

View the status of the database server. Examples are shown below:

{"host": "Dev", "version": "...", "process": "Mongod", "uptime":, "uptimeestimate":, "LocalTime": Isodate ("--T::.") Z ")," GlobalLock ": {" TotalTime ":," Locktime ":," ratio ":.," Currentqueue " 
             : {"Total":, "Readers":, "Writers":}, "Activeclients": {
         "Total":, "Readers":, "Writers":}}, "Mem": { "Bits":, "resident":, "virtual":, "Supported": TRUE, "mapped":}, " Connections ': {' current ':, ' available ':}, ' Extra_info ': {' note ': ' Fields va Ry by platform "," heap_usage_bytes ":," Page_faults ":}," Indexcounters ": {" Btre
     E ": {" accesses ":," hits ":," misses ":," resets ":,        "Missratio":.
         }, "backgroundflushing": {"Flushes":, "Total_ms":, "Average_ms":., "Last_ms":, "last_finished": Isodate ("--T::.")
     Z ")}," Cursors ": {" Totalopen ":," clientcursors_size ":," TimedOut ":},
         "Network": {"Bytesin":, "Bytesout":, "Numrequests":}, "Opcounters": { "Insert":, "Query":, "Update":, "delete":, "Getmore":, "com
         Mand ":}," asserts ": {" regular ":," Warning ":," MSG ":," User ":,  "Rollovers":}, "writebacksqueued": false, "OK":}

Sometimes, by looking at the state of the database server, you can determine whether there is a problem with the database, if there is a problem, such as data corruption, you can perform the repair in time.

5, query the specified database statistics information

Use fragment
db.stats ()

The query results are shown in the following example:

Db.stats ()
 {"
 db": "Fragment",
 "collections":,
 "Objects":,
 "Avgob  Jsize ":.,
 " DataSize ":,
 " Storagesize ":,
 " numextents ":,
 " Indexes " :,
 "Indexsize":,
 "fileSize":, "
 OK": 
 

Displays statistics about the fragment database.

6, query the specified database contains the list of collection names

Db.getcollectionnames ()

The results are as follows:

Db.getcollectionnames ()
 [
     "U",
     "Basese",
     "Bytravel",
     "Daodao",
     "Goeu",
     "Lotour",
     "Lvping",
     "Mafengwo",
     "Sina",
     "Sohu",
     "System.indexes"
 

(ii) Basic DDL and DML

1. Create a database

If you are accustomed to relational databases, you may be looking for related commands to create a database. In MongoDB, you can switch directly to the database context by using the use dbname, and the system automatically delays the creation of the database, for example:

 Show dbs
 admin  . GB
 local  (empty)
 pagedb. GB
 Test  . GB use
 luceneindexdb
 switched to DB luceneindexdb show
 dbs
 admin  . GB
 local  (empty)
 pagedb. GB
 Test  . GB
 db
 luceneindexdb
 db.storeCollection.save (' Version ': '. ', ' segment ': ' EOL '}) show
 dbs
 Luceneindexdb  . GB
 admin  . GB
 local  (empty)
 pagedb. GB
 Test  . GB

Visible, the database and collection are created after the use of the specified database, and after inserting the data into one of the specified sets.

2, delete the database

You can delete a database directly using Db.dropdatabase ().

3. Create a Collection

You can use the command db.createcollection (name, {size: ..., capped: ..., max: ...}) Create a collection, as shown in the following example:

4, delete the collection

Deletes a collection to perform db.mycoll.drop ().

5. Insert Update record

Use the Save method of the collection directly, as follows:

 

Update the record, and using save overwrites the original record value to implement the record update.

6, query a record

Using the FindOne () function, the parameter is a query condition, optionally, the system randomly retrieves a record that satisfies the condition (if there is a query result number greater than or equal to 1), as follows:

7, query more than one record

Using the Find () function, the parameter specifies the query condition, and all records are queried without specifying criteria.

8, delete the record

Using the Remove () method of the collection, the parameter is specified as a query condition, as shown in the following example:

 Db.storeCollection.remove ({' Version ': '. '})
 Db.storeCollection.findOne ()
 

9. CREATE index

You can use the Ensureindex (Keypattern[,options]) method of the collection, as shown in the following example:

Use Pagedb
switched to DB pagedb
Db.page.ensureIndex ({' title ':, ' url ':-})
Db.system.indexes.find ()
 {' name ': ' _id_ ', ' ns ': ' Pagedb.page ', ' key ': {' _id ':}, ' V ':}
 {' name ': ' _id_ ', ' ns ': ' pagedb.system.users ', ' key ': {' _id ':}, ' V ':}
 {"_id": ObjectId ("EFCFCACCD"), "ns": "Pagedb.page", "key": {"title":, "url":-}, "name": "title__url_-", "V":}

Above, in the Ensureindex method argument, the number 1 represents ascending, and-1 indicates descending.

Use Db.system.indexes.find () to query all indexes.

10. Query Index

The index that we set up for the collection, you can implement the query through the Getindexes () method of the collection, as shown below:

 Db.page.getIndexes ()
 [
     {
         ' name ': ' _id_ ',
         ' ns ': ' Pagedb.page ',
         ' key ': {
             ' _id ': 
         },
         "V": 
     },
     {
         "_id": ObjectId ("EFCFCACCD"),
         "ns": "Pagedb.page",
         "key": {
             "title":,
             "url":-
         },
         "name": "title__url_-",
         "V": 
     }
 ]

Of course, if you need to query all the indexes in your system, you can use the Db.system.indexes.find () function.

11. Delete Index

There are two ways to delete an index:

Db.mycoll.dropIndex (name)
  

The first deletes the entire index of the specified collection by specifying an index name.

12. Index reconstruction

You can rebuild the index through the Reindex () method of the collection, as shown in the following example:

Use fragment
Db.baseSe.count ()

Statistical results, as follows:

 Use fragment
 switched to db fragment
 Db.baseSe.count ()

The above statistics the number of records in the Basese collection of the database fragment.

14, query and statistics results record number

 Use fragment
Db.baseSe.find (). Count ()

Find () can provide query parameters, and then query and count the results as follows:

15, query the collection of the specified database currently available storage space

Use fragment
db.baseSe.storageSize ()
142564096

16. Query The storage space allocated by the collection of the specified database

Db.baseSe.totalSize ()
 144096000

The above query results include the storage space allocated for the collection (data and its indexed storage).

(iii) Initiation and termination

1. Normal start-up

Mongod--dbpath/usr/mongo/data--logfile/var/mongo.log

Description

Specify the data store directory and log directory, and if the security authentication mode is used, you need to add the--auth option, such as:

 
 

2. Start with Repair mode

Mongod--repair

Start the database in Repair mode.

It is very likely that the database data corruption or inconsistent data state, resulting in the failure to start the MongoDB server normally, depending on the startup information you can see the need for repair. or execute:

Mongod-f/etc/mongodb.conf--repair

3. Terminate Server process

Db.shutdownserver ()

Terminates the database server process. Alternatively, you can kill the Mongod process directly.

(iv) Safety management

1, the security certification mode to start

Mongod--auth--dbpath/usr/mongo/data--logfile/var/mongo.log

You can enable authentication mode by starting the Mongod process with the--auth option.

Alternatively, you can modify the/etc/mongodb.conf, set the auth=true, and restart the Mongod process.

2, add Users

Db.adduser ("admin", ",%f23_kj~00opoo0+\/")

Adding a database user, adding a success, the results are shown as follows:

Db.auth ("admin", ",%f23_kj~00opoo0+\/")

Database security certification. Certificate Successful Display results:

 {
     "user": "admin",
     "readOnly": false,
     "pwd": "DEBFCBABBECD"
 

If you are an authenticated user, you can perform certain commands to see the correct execution of the results, as follows:

4. Write Data for database (sync to disk) lock

Db.runcommand ({fsync:1,lock:1})

Description

This operation has been locked to the database and does not allow write data operations, which are generally useful when performing database backups. Execute the command, and the result example is as follows:

5. View current lock status

Db.currentop ()

Description

The results of the query are as follows:

6, Unlock

 Use admin
db. $cmd. Sys.unlock.findOne ()

Description

To perform the unlock, the result is as follows:

Db.currentop ()

The status information is as follows:

(v) Data backup, recovery and migration management

1. Back Up all databases

mkdir testbak
cd Testbak
mongodump

Note: The default backup directory and data file format is./dump/[databasename]/[collectionname].bson

2, backup the specified database

Mongodump-d Pagedb

Description: Backs up data in the database Pagedb.

3. Back up a collection in a database

mongodump-d pagedb-c Page

Description: Backs up the database Pagedb page collection.

4. Restore all databases

CD Testbak
Mongorestore--drop

Note: Restore all the databases of the backup to the database,--drop the original database data before you specify the recovery data, or it will result in duplicate data in the reply.

5, restore the data of a database

CD Testbak
mongorestore-d pagedb--drop

Description: Restores the backed-up pagedb data to the database.

6, restore the data of a collection of a database

CD testbak
mongorestore-d pagedb-c page--drop

Description: Restores the data from the Pagedb page collection of the backup to the database.

7. Import data to MongoDB

mongoimport-d pagedb-c page--type csv--headerline--drop < csvortsvfile.csv

Description: Imports the file csvortsvfile.csv data into the page collection of the Pagedb database, using the name of the column in the CVS or TSV file as the column name for the collection. It should be noted that only CSV and TSV files are supported when using the--headerline option.

There are three types supported by--type: CSV, TSV, JSON
Use of the other options to view Help:

Mongoexport-d pagedb-c Page-q {}-F _id,title,url,spidername,pubdate--csv > Pages.csv

Description: Exports the data from the page collection in the Pagedb database to the Pages.csv file, with each option meaning:

-f Specifies the CVS column named _id,title,url,spidername,pubdate
-Q Specify query criteria

Use of the other options to view Help:

If the above option-q specifies a query condition, it needs to be enclosed in single quotes, as follows:

Otherwise, you receive the following error:

1. Implement remote connection based on MONGO

When you have connected to a remote MongoDB database server (for example, by connecting to 192.168.0.184 via MONGO), now want to connect to another remote database server (192.168.0.197) in this session, you can execute the following command:

If security authentication mode is enabled, you can specify the authentication account when you obtain a database connection instance.

Well, this article to introduce you to the MongoDB Management command to the end, I hope this article to share can bring help to everyone.

Related Article

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.