Detail the MongoDB administrative command

  • 2020-05-15 02:28:57
  • OfStack

MongoDB is an NoSQL database system: a database can contain multiple collections (Collection), each of which corresponds to a table in a relational database. Each collection can store 1 set of records identified by columns, which are freely defined and flexible, and the collection of entities identified by 1 set of columns corresponds to rows in a relational database table. Let's take a look at the basic functions and behaviors of DBMS provided by MongoDB by familiarizing ourselves with the basic administrative commands of MongoDB.

MongoDB command help system

After installing MongoDB, start the server process (mongod), and you can manage and monitor MongoDB by ordering mongo on the client side. Take a look at MongoDB's command help system:


 root@dev:~# mongo
 MongoDB shell version: ..
 connecting to: test
 > help
     db.help()          help on db methods
     db.mycoll.help()       help on collection methods
     rs.help()          help on replica set methods
     help connect         connecting to a db help
     help admin          administrative help
     help misc          misc things to know
     help mr           mapreduce help
     show dbs           show database names
     show collections       show collections in current database
     show users          show users in current database
     show profile         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.find( { a : } )   list objects in foo where a == 
     it              result of 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-level command list of MongoDB, which mainly tells us some abstract categories related to database management: database operation help, collection operation help, and management help. If you want to know more about the database operation help command, you can directly use db.help (), as shown below:


 db.help()
 DB methods:
     db.addUser(username, password[, readOnly=false])
     db.auth(username, password)
     db.cloneDatabase(fromhost)
     db.commandHelp(name) returns the help for the command
     db.copyDatabase(fromdb, todb, fromhost)
     db.createCollection(name, { size : ..., capped : ..., max : ... } )
     db.currentOp() displays the current operation in the db
     db.dropDatabase()
     db.eval(func, args) run code server-side
     db.getCollection(cname) same as db['cname'] or db.cname
     db.getCollectionNames()
     db.getLastError() - just returns the err msg string
     db.getLastErrorObj() - return full status object
     db.getMongo() get the server connection 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 profiling is on and slow threshold 
     db.getReplicationInfo()
     db.getSiblingDB(name) get the db at the same server as this one
     db.isMaster() check replica primary status
     db.killOp(opid) kills the current operation in the db
     db.listCommands() lists all the db commands
     db.printCollectionStats()
     db.printReplicationInfo()
     db.printSlaveReplicationInfo()
     db.printShardingStatus()
     db.removeUser(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 

Basic commands for database management and operation can be obtained from above. For more, and more detailed usage of each command, you can use the db.listCommands () query listed above.

The other one is based on the operation, management and monitoring of the collection of the specified database, 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.mycoll.dataSize()
     db.mycoll.distinct( key ) - eg. db.mycoll.distinct( 'x' )
     db.mycoll.drop() drop the collection
     db.mycoll.dropIndex(name)
     db.mycoll.dropIndexes()
     db.mycoll.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
     db.mycoll.reIndex()
     db.mycoll.find([query],[fields]) - query is an optional query filter. fields is optional 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': false] } )
     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)
     db.mycoll.renameCollection( newName , <dropTarget> ) renames the collection.
     db.mycoll.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
     db.mycoll.save(obj)
     db.mycoll.stats()
     db.mycoll.storageSize() - includes free space allocated to this collection
     db.mycoll.totalIndexSize() - size in bytes of all the indexes
     db.mycoll.totalSize() - storage allocated 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 

Database and collection management related commands, is the most basic and most commonly used, such as collection queries, index operations, and so on.

Basic commands and examples

Here's a practical example of some common commands:

(1) basic command

1, show dbs

Displays the database on the current database server

2, use pagedb

Switch to the context of the specified database pagedb, where you can manage the pagedb database, its collections, and so on

3, show collections

Display all collections in the database (collection)

4, db. serverStatus ()

View the status of the database server. An example is 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 vary by platform",
         "heap_usage_bytes" : ,
         "page_faults" : 
     },
     "indexCounters" : {
         "btree" : {
             "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" : ,
         "command" : 
     },
     "asserts" : {
         "regular" : ,
         "warning" : ,
         "msg" : ,
         "user" : ,
         "rollovers" : 
     },
     "writeBacksQueued" : false,
     "ok" : 
 } 

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

5. Query to specify database statistics


use fragment
db.stats()

An example of the query result is shown below:


db.stats()
 {
         "db" : "fragment",
         "collections" : ,
         "objects" : ,
         "avgObjSize" : .,
         "dataSize" : ,
         "storageSize" : ,
         "numExtents" : ,
         "indexes" : ,
         "indexSize" : ,
         "fileSize" : ,
         "ok" : 
 } 

Displays statistics for the fragment database.

Query the specified database contains a 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"
 ] 

(2) basic DDL and DML

1. Create a database

If you're used to relational databases, you might want to look for commands to create them. In MongoDB, you can switch to the database context directly via use dbname, and the system will automatically delay 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

As you can see, after use specifies the database and inserts data into one of the specified collections, both the database and the collection are created.

2. Delete the database

You can delete the database directly using db.dropDatabase ().

Create a collection

You can use the command db.createCollection (name, {size:... , capped:... , max:... }) create a collection, as shown below:

4. Delete the collection

Delete the collection to perform db.mycoll.drop ().

5. Insert update record

Directly use the save method of the collection, as shown below:


 <em>db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})</em> 

Update the record, using save will overwrite the original record value to realize the record update.

6. Query one record

Using the findOne() function, the parameter is the query condition. Optionally, the system will randomly query and obtain a record that meets the condition (if the number of query results is greater than or equal to 1), as shown below:

7. Query multiple records

Using the find() function, the query conditions are specified as parameters, and all records are queried if no conditions are specified.

8. Delete records

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


 db.help()
 DB methods:
     db.addUser(username, password[, readOnly=false])
     db.auth(username, password)
     db.cloneDatabase(fromhost)
     db.commandHelp(name) returns the help for the command
     db.copyDatabase(fromdb, todb, fromhost)
     db.createCollection(name, { size : ..., capped : ..., max : ... } )
     db.currentOp() displays the current operation in the db
     db.dropDatabase()
     db.eval(func, args) run code server-side
     db.getCollection(cname) same as db['cname'] or db.cname
     db.getCollectionNames()
     db.getLastError() - just returns the err msg string
     db.getLastErrorObj() - return full status object
     db.getMongo() get the server connection 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 profiling is on and slow threshold 
     db.getReplicationInfo()
     db.getSiblingDB(name) get the db at the same server as this one
     db.isMaster() check replica primary status
     db.killOp(opid) kills the current operation in the db
     db.listCommands() lists all the db commands
     db.printCollectionStats()
     db.printReplicationInfo()
     db.printSlaveReplicationInfo()
     db.printShardingStatus()
     db.removeUser(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 
0

9. Create indexes

You can use the ensureIndex(keypattern[,options]) method of the collection, as shown below:


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" : }

In the above ensureIndex method parameters, the number 1 represents ascending order and -1 represents descending order.

Using db. system. indexes. find () can query all indexes.

10. Query the index

The index we built for the collection can be queried using the getIndexes() method of the collection, as shown in the following example:


 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 index in the system, can use db. system. indexes. find () function.

11. Drop the index

Dropping an index gives two methods:


 db.help()
 DB methods:
     db.addUser(username, password[, readOnly=false])
     db.auth(username, password)
     db.cloneDatabase(fromhost)
     db.commandHelp(name) returns the help for the command
     db.copyDatabase(fromdb, todb, fromhost)
     db.createCollection(name, { size : ..., capped : ..., max : ... } )
     db.currentOp() displays the current operation in the db
     db.dropDatabase()
     db.eval(func, args) run code server-side
     db.getCollection(cname) same as db['cname'] or db.cname
     db.getCollectionNames()
     db.getLastError() - just returns the err msg string
     db.getLastErrorObj() - return full status object
     db.getMongo() get the server connection 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 profiling is on and slow threshold 
     db.getReplicationInfo()
     db.getSiblingDB(name) get the db at the same server as this one
     db.isMaster() check replica primary status
     db.killOp(opid) kills the current operation in the db
     db.listCommands() lists all the db commands
     db.printCollectionStats()
     db.printReplicationInfo()
     db.printSlaveReplicationInfo()
     db.printShardingStatus()
     db.removeUser(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 
3

The first deletes all indexes of the specified collection by specifying the index name, and the second deletes all indexes of the specified collection.

12. Index reconstruction

The index can be reconstructed using the reIndex() method of the collection, as shown in the following example:


 db.help()
 DB methods:
     db.addUser(username, password[, readOnly=false])
     db.auth(username, password)
     db.cloneDatabase(fromhost)
     db.commandHelp(name) returns the help for the command
     db.copyDatabase(fromdb, todb, fromhost)
     db.createCollection(name, { size : ..., capped : ..., max : ... } )
     db.currentOp() displays the current operation in the db
     db.dropDatabase()
     db.eval(func, args) run code server-side
     db.getCollection(cname) same as db['cname'] or db.cname
     db.getCollectionNames()
     db.getLastError() - just returns the err msg string
     db.getLastErrorObj() - return full status object
     db.getMongo() get the server connection 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 profiling is on and slow threshold 
     db.getReplicationInfo()
     db.getSiblingDB(name) get the db at the same server as this one
     db.isMaster() check replica primary status
     db.killOp(opid) kills the current operation in the db
     db.listCommands() lists all the db commands
     db.printCollectionStats()
     db.printReplicationInfo()
     db.printSlaveReplicationInfo()
     db.printShardingStatus()
     db.removeUser(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 
4

The statistical results are as follows:


 db.help()
 DB methods:
     db.addUser(username, password[, readOnly=false])
     db.auth(username, password)
     db.cloneDatabase(fromhost)
     db.commandHelp(name) returns the help for the command
     db.copyDatabase(fromdb, todb, fromhost)
     db.createCollection(name, { size : ..., capped : ..., max : ... } )
     db.currentOp() displays the current operation in the db
     db.dropDatabase()
     db.eval(func, args) run code server-side
     db.getCollection(cname) same as db['cname'] or db.cname
     db.getCollectionNames()
     db.getLastError() - just returns the err msg string
     db.getLastErrorObj() - return full status object
     db.getMongo() get the server connection 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 profiling is on and slow threshold 
     db.getReplicationInfo()
     db.getSiblingDB(name) get the db at the same server as this one
     db.isMaster() check replica primary status
     db.killOp(opid) kills the current operation in the db
     db.listCommands() lists all the db commands
     db.printCollectionStats()
     db.printReplicationInfo()
     db.printSlaveReplicationInfo()
     db.printShardingStatus()
     db.removeUser(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 
5

The above counts the number of records in the baseSe collection of database fragment.

14. Query and count the number of records


 db.help()
 DB methods:
     db.addUser(username, password[, readOnly=false])
     db.auth(username, password)
     db.cloneDatabase(fromhost)
     db.commandHelp(name) returns the help for the command
     db.copyDatabase(fromdb, todb, fromhost)
     db.createCollection(name, { size : ..., capped : ..., max : ... } )
     db.currentOp() displays the current operation in the db
     db.dropDatabase()
     db.eval(func, args) run code server-side
     db.getCollection(cname) same as db['cname'] or db.cname
     db.getCollectionNames()
     db.getLastError() - just returns the err msg string
     db.getLastErrorObj() - return full status object
     db.getMongo() get the server connection 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 profiling is on and slow threshold 
     db.getReplicationInfo()
     db.getSiblingDB(name) get the db at the same server as this one
     db.isMaster() check replica primary status
     db.killOp(opid) kills the current operation in the db
     db.listCommands() lists all the db commands
     db.printCollectionStats()
     db.printReplicationInfo()
     db.printSlaveReplicationInfo()
     db.printShardingStatus()
     db.removeUser(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 
6

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

Query the currently available storage space for a collection of specified databases


use fragment
db.baseSe.storageSize()
142564096

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 index store).

(3) start and stop

1. Normal startup


 db.help()
 DB methods:
     db.addUser(username, password[, readOnly=false])
     db.auth(username, password)
     db.cloneDatabase(fromhost)
     db.commandHelp(name) returns the help for the command
     db.copyDatabase(fromdb, todb, fromhost)
     db.createCollection(name, { size : ..., capped : ..., max : ... } )
     db.currentOp() displays the current operation in the db
     db.dropDatabase()
     db.eval(func, args) run code server-side
     db.getCollection(cname) same as db['cname'] or db.cname
     db.getCollectionNames()
     db.getLastError() - just returns the err msg string
     db.getLastErrorObj() - return full status object
     db.getMongo() get the server connection 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 profiling is on and slow threshold 
     db.getReplicationInfo()
     db.getSiblingDB(name) get the db at the same server as this one
     db.isMaster() check replica primary status
     db.killOp(opid) kills the current operation in the db
     db.listCommands() lists all the db commands
     db.printCollectionStats()
     db.printReplicationInfo()
     db.printSlaveReplicationInfo()
     db.printShardingStatus()
     db.removeUser(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 
9

Description:

Specify the data storage directory and log directory. If security authentication mode is used, add the --auth option, such as:


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

2. Start in repair mode


mongod --repair

Start the database in repair mode.

In fact, it is very likely that the database data is corrupted or the data state is not 1, so the MongoDB server cannot be started normally. According to the startup information, we can see that it needs to be repaired. Or execute:


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

3. Terminate the server process


db.shutdownServer()

Terminates the database server process. Alternatively, you can simply kill the mongod process.

(4) safety management

1. Start in security authentication mode


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

Start the mongod process with the --auth option to enable authentication mode.

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

2. Add users


db.addUser("admin", ",%F23_kj~00Opoo0+\/")

Add database user, add successfully, then display the result as follows:


db.auth("admin", ",%F23_kj~00Opoo0+\/")

Database security authentication. Results of successful authentication:


 {
     "user" : "admin",
     "readOnly" : false,
     "pwd" : "debfcbabbecd"
 } 

If you are an authenticated user, execute some commands and you will see the correct execution results, as shown below:

Write to the database (synchronize to disk) and lock it


db.runCommand({fsync:1,lock:1})

Description:

This operation has been locked to the database and is not allowed to perform write data operations. 1 is generally useful when performing database backups. Execute the command, and the results are as follows:

5. Check the current lock status


db.currentOp()

Description:

The query results are as follows:

6, unlock


 use admin
db.$cmd.sys.unlock.findOne()

Description:

Execute the unlock, and the result is as follows:


db.currentOp()

The status information is as follows:

(5) data backup, recovery and migration management

1. Backup 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

Note: back up the data in database pagedb.

Back up a collection in a database


mongodump -d pagedb -c page

Description: backup database pagedb page collection.

4. Restore all databases


cd testbak
mongorestore --drop

Note: restore all the backup databases to the database, --drop specifies to delete the original database data before restoring the data, otherwise the data in the recovered data will be duplicated.

5. Restore data from a database


cd testbak
mongorestore -d pagedb --drop

Note: restore the backup pagedb data to the database.

6, restore a database of a collection of data


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

Note: restore the backup data of pagedb's page collection to the database.

7. Import data to MongoDB


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

Note: import the data from file csvORtsvFile.csv into the page collection of the pagedb database, using the column name of the cvs or tsv files as the column name of the collection. It is important to note that when using the --headerline option, only csv and tsv files are supported.

--type supports three types: csv, tsv, json
For other options, see help:


mongoexport -d pagedb -c page -q {} -f _id,title,url,spiderName,pubDate --csv > pages.csv

Description: export the data of page collection in pagedb database to pages.csv file.

- f cvs specified column names for _id title, url, spiderName, pubDate
-q specifies query conditions

For other options, see help:

If the above option -q specifies 1 query condition, it should be enclosed in single quotes, as follows:

Otherwise, the following error occurs:

1. Remote connection is realized based on mongo

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

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

Well, that's the end of the MongoDB administrative command that I've introduced you to in this article.


Related articles: