Basic MongoDB Commands
db.help() get a list of commands
show dbs print a list of all databases on the server
use myTestDB create new database "myTestDB"
db know your current selected database
db.dropDatabase() drop the current selected database
db.createCollection("Employee") create new collection "Employee"
show collections print a list of all collections created
db.Employee.drop() drop the collection "Employee"
db.Employee.insert({name: 'Raj', address: insert document in collection "Employee"
'Bangalore'})
db.Employee.find() list the documents in collection "Employee"
{ "_id" : ObjectId("60658a0dbe02cfa1d386ab52"), "name" : "Raj", "address" : "Bangalore" }
db.Employee.update({'name' : 'Raj'}, update the document in collection "Employee"
{$set: {'name' : 'Albert'}})
db.Employee.find() list the documents in collection "Employee"
{ "_id" : ObjectId("60658a0dbe02cfa1d386ab52"), "name" : "Albert", "address" : "Bangalore" }
save document in collection "Employee"
db.Employee.save({"_id": new
ObjectId("60658a0dbe02cfa1d386ab53"),
name: "Newton", address: "Delhi"});
db.Employee.find() list the documents in collection "Employee"
{ "_id" : ObjectId("60658a0dbe02cfa1d386ab52"), "name" : "Albert", "address" : "Bangalore" }
{ "_id" : ObjectId("60658a0dbe02cfa1d386ab53"), "name" : "Newton", "address" : "Delhi" }
db.Employee.remove({'name': 'Albert'}) delete document in collection "Employee"
db.Employee.find() list the documents in collection "Employee"
{ "_id" : ObjectId("60658a0dbe02cfa1d386ab53"), "name" : "Newton", "address" : "Delhi" }
db.getUsers(); list down all the users of current database
show roles list down all the roles
db.Employee.dataSize() get the size of the collection "Employee"
db.Employee.storageSize() get the total size of document stored in the
collection "Employee"
db.Employee.totalSize() get the total size in bytes for both collection
data and indexes
db.Employee.totalIndexSize() get the total size of all indexes in the
collection "Employee"