Getting to Know the Common MongoDB Commands

Getting to Know the Common MongoDB Commands

In this post, we'll break down and study the most popular commands that can be used on mongoDB databases and if you want to learn how to create databases on mongodb using different methods, try checking out our article about it here. Managing MongoDB databases with these commands will help you setup and become comfortable with the mongoDB database platform.

MongoDB Help

To get a list of commands, type

 db.help()

in MongoDB client.

Log Into MongoDB

To log into the MongoDB database, run the following command.

Check if the user with the credentials username and password exists in the database specified in place of dbname.

mongo -u  -p  --authenticationDatabase 

Show All Databases

Once signed in as a user with the proper role, such as userAdmin or userAdminAnyDatabase, the user may view all databases by using the command

showdbs

Select Database to Work With

To begin working with a specific database, run the following command:

use databaseName

Authenticate and Log Out From Database

When using the use dbName command to switch to a different database, the user must authenticate using a valid database user for that database. For authentication, run the following command:

db.auth("username", "password");

If you're done with your work with the database and want to logout, Just simply type:

db.logout()

List Down Collections, Users, Roles

To check existing collections, users, and so on, use the following commands.

List down collections of the current database

show collections;
db.getCollectionNames();

List down all the users of all current database

show users;
db.getUsers();

List down all the roles


Create a Collection

To make a collection, use the following command. This page contains further information on this command if you want a more in-depth guide on this.

db.createCollection("collectionName");

Insert a Document in a Collection

After creating a collection, the following step is to input one or more documents. A example command for inserting a document into a collection is shown below.

Insert single document

db..insert({field1: "value", field2: "value"})

Insert multiple documents

db..insert([{field1: "value1"}, {field1: "value2"}])db.
.insertMany([{field1: "value1"}, {field1: "value2"}])

Save or Update Document

Depending on the document parameter supplied to it, the save command can be used to either edit an existing document or insert a new one. If the _id given is the same as that of an existing document, the document is updated. If not, a new document is produced. The insert or update command is used internally by the save mechanism.

If a matching document is located, it is modified; if none is found, a new document is produced.

db..save({"_id": new ObjectId("objectname"), field1: "value", field2: "value"});

Display Collection Records

The following commands can be used to retrieve collection records:

Retrieve all records

db..find();

Retrieve limited number of records; Following command will print 10 results; if you're looking for a larger record, simply change the number

db..find().limit(10);

Retrieve records by id

db..find({"_id": ObjectId("userspecifiedid")});

Retrieve values for certain collection attributes by giving an object with attribute names set to 1 or 0 depending on whether the attribute value should be included in the output or not.

db..find({"_id": ObjectId("userspecifiedid")}, {field1: 1, field2: 1});
db..find({"_id": ObjectId("userspecifiedid")}, {field1: 0}); // Exclude field1

Collection count

db..count();

Administrative Commands

The administrative commands listed below can help you find collection details such as storage size, total size, and overall statistics.

Get the collection statistics

db..stats()
db.printCollectionStats()

Latency metrics for read and write operations, including average read and write times and the number of operations executed

db..latencyStats()

Get collection size for data and indexes

db..dataSize()

Size of the collection

db..storageSize()

The total size of documents stored in the collection

db..totalSize()

The total size of all indexes in the collection

db..totalIndexSize()

Connect to MongoDB database

Once you've downloaded and installed MongoDB, you can use the mongo shell to connect to an active MongoDB server. Note: Your server must be operational before you connect to it using the shell. You can start the server in CMD using the following command:

net start MongoDB

Then type the mongo command to run the shell.

Mongo

 

Now you are in the Mongo shell.

You can launch mongo and mongod without using the command prompt if you choose. To do so, navigate to the installation directory and double-click the mongod and mongo apps. You will obtain the same result as in the previous example.

Different port

The above mongo command will only function if your MongoDB server is listening on port 27017. If your MongoDB server uses a different port, you must mention it explicitly in the command, as demonstrated below:

mongo --port 28010

Remote server

Both of the above instructions are only valid if your MongoDB server is operating on localhost. Use the '-host' argument with the mongo command to connect to a remote server, as demonstrated below.

mongo --host mongodb0.example.com --port 28010

Conclusion

Starting out your database journey in any platform can be difficult, but with the right research you can master and harness these commands to your will and help you manage your databases easier! Trying out Automated Backups like Ottomatik can be a huge help especially if you're managing a huge amount of projects and will save you from major headaches if an accident happens!

Ready to secure your backups today?

Try for free