Introduction
The mongo shell is an interactive JavaScript interface to MongoDB
Learn more: https://docs.mongodb.com/v4.4/mongo/
The mongo shell is included as part of the MongoDB server installation. If you have already installed the server, the mongo shell is installed in the same location as the server binary.
Contents
- Into mongo shell
- Verify Databases with show dbs command
- Listing MongoDB commands
- Stats of DataBase
- Get Data from Collection and Check Collection name
- Drop DataBase or Collection
1. Into mongo shell
mongo
MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2249e599-64e9-4e43-b1ba-a20578cdbb68") }
MongoDB server version: 4.4.1
---
The server generated these startup warnings when booting:
2020-11-07T11:49:06.648+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
2020-11-07T11:49:08.593+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>
the database you are using, type db:
> db
test
The operation should return test, which is the default database.
2. Verify Databases with show dbs command
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
stock 0.000GB
- stock database is example
3. Listing MongoDB commands
> db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
db.auth(username, password)
db.cloneDatabase(fromhost) - will only function with MongoDB 4.0 and below
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost) - will only function with MongoDB 4.0 and below
db.createCollection(name, {size: ..., capped: ..., max: ...})
db.createUser(userDocument)
db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
db.currentOp() displays currently executing operations in the db
db.dropDatabase(writeConcern)
db.dropUser(username)
db.eval() - deprecated
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnlock() unlocks server following a db.fsyncLock()
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getLogComponents()
db.getMongo() get the server connection object
db.getMongo().setSecondaryOk() allow queries on a replication secondary server
db.getName()
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.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
db.hostInfo() get details about the server's host
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.loadServerScripts() loads all the scripts in db.system.js
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printShardingStatus()
db.printSecondaryReplicationInfo()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj: 1}
db.serverStatus()
db.setLogLevel(level,<component>)
db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
db.setVerboseShell(flag) display extra information in shell output
db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
db.shutdownServer()
db.stats()
db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
db.version() current version of the server
db.watch() - opens a change stream cursor for a database to report on all changes to its non-system collections.
4. Stats of DataBase
> db.stats()
{
"db" : "stock",
"collections" : 1,
"views" : 0,
"objects" : 248,
"avgObjSize" : 435.8790322580645,
"dataSize" : 108098,
"storageSize" : 53248,
"indexes" : 1,
"indexSize" : 36864,
"totalSize" : 90112,
"scaleFactor" : 1,
"fsUsedSize" : 4131966976,
"fsTotalSize" : 8259014656,
"ok" : 1
}
5. Get Data from Collection and Check Collection name
> use stock
switched to db stock
> db.getCollectionNames()
[ "stocks" ]
> db.stocks.find()
{ "_id" : ObjectId("5fa689eb8f8f950011b2fe45"), "created" : ISODate("2020-11-07T11:50:03.259Z"), "__v" : 0 }
> db.stocks.find().pretty()
{
"_id" : ObjectId("5fa68a548f8f950011b2fe58"),
"created" : ISODate("2020-11-07T11:51:48.228Z"),
"__v" : 0
}
- stocks collection is example in stock database
6. Drop DataBase or Collection
> use stock
switched to db stock
> db.dropDatabase()
{ "dropped" : "stock", "ok" : 1 }
> use stock
switched to db stock
> show collections
stocks
> db.stocks.drop()
true