MongoDB

Most useful commands for MongoDB

MongoDB belongs to the NoSQL category of databases and is well known for its strong querying system. MongoDB uses its own querying language known as MQL (MongoDB Query Language) to perform processing on data. MQL supports an extensive list of commands that are quite helpful in several Mongo-based operations.

The commands in MongoDB can be used for CRUD operations to get information about databases and their collections. Other operations provided by MongoDB commands may include creating new users and assigning roles to them. In this informative post, we will list down the most useful commands in MongoDB, and it would be beneficial for MongoDB beginners as well as the current users of MongoDB.

Most useful commands for MongoDB

This section provides a deep insight into MongoDB commands and their usage. The commands in the section are broadly categorized into three categories.

Commands related to databases and their collections

All the commands are used to perform some operation on either a database or a collection. Here, we will list down the most useful commands that guide to perform operations that are directly related to a database or a collection. Like, creating, removing, truncating a collection or a database.

1: use

The use command in MongoDB can be executed to create a new database or switch to an existing one. The syntax of this command is given below:

> use <database-name>

The following command will create a database named “linuxhint“:

> use linuxhint

The use command in MongoDB is exercised to create a new database, and it switches you to that database as well.

2: db

The db command will assist you to check the name of the database (on which you are currently working). The syntax for this command is provided below:

> db

The command written below will show the name of the current database:

> db

3: show dbs

You can get the list of the databases that you have created so far and the default databases as well. For this, this command can be executed as shown below:

> show dbs

4: show databases

The names of databases and their sizes can also be retrieved by using “show databases“. This command can be executed as displayed below:

> show databases

Note: It is observed that “show dbs” and “show databases” commands do not retrieve those databases that have not been inserted with some documents.

5: db.stats()

The stats command displays the statistics of the current database. The statistics contain detailed information about that database, like its name, the number of collections inside it, the number of objects, the size of each object, and many more.

For database: The command written below will display the statistical information of the current database:

> db.stats()

For a collection: You can check the stats of a collection as well. In our case, the following command will show the statistical information of the “distros” collection:

> db.distros.stats()

6: dropDatabase()

The databases can be dropped using the below-mentioned command. By dropping, the documents and the database are removed from the MongoDB server. The below-mentioned command will drop the “ford” database from the MongoDB server.

> db.dropDatabase()

7: db.createCollection(“”)

MongoDB works on the collection and associated documents. You can create a collection with the help of the syntax provided below:

> db.creatCollection("collection-name")

The command mentioned below will create a collection of “linux” in the database you are logged in to.

> db.createCollection("linux")

8: show collections

The collection’s names on your MongoDB server can be obtained by using this command. For instance, in our case, the following command listed the names of collections that are associated with databases.

> show collections

9: dataSize, storageSize, totalSize, totalIndexSize

MongoDB allows you to get the dataSize, storageSize, totalSize and totalIndexSize of any collection. These can also be found collectively using stats() as we did in the above example. For instance, we have executed the command written below to get all the information of “distros” collection:

To get the dataSize, use dataSize() to get the size of data inside a collection:

> db.distros.dataSize()

To get storage size, use storageSize() as it is executed below:

> db.distros.storageSize()

10: drop() “drop a collection”

MongoDB allows you to drop a collection of a MongoDB database. For instance, in our case the below-mentioned command will drop “store” collection from the MongoDB database:

> db.store.drop()

11: remove() “truncate a collection”

Instead of dropping, you can truncate a collection as well. By this, only documents are deleted, the collection does not. The below mentioned command will remove the documents in “inventory” collection:

> db.inventory.remove({})

Commands related to CRUD operations

The CRUD operations are a core part of any database management system. In this section, we have provided the commands that assist you in performing CRUD operations in MongoDB:

The insertion of documents in a MongoDB collection can be carried out in several ways. For instance, to insert a single document, you may use “insertOne()“. Moreover, for multiple insertions insert(), or insertMany() are used.

12: insertOne() “insert one document”

The insertOne() method in MongoDB assists you to insert only one document. The following syntax should be followed for one insertion.

> db.collection-name.insertOne({<field1>: <value>, <field2>: <value>})

The command written below will insert only one document in “employees” collection:

> db.employees.insertOne({name: "Sam", designation: "Team-Lead"})

13: insert() “insert one or multiple documents”

This command is used to insert a single or multiple documents. Syntax to insert single document:

> db.collection-name.insert({<ield1: value>, <field2: value>})

The command written below shows the insertion of a single document in “distributions” collection:

> db.distributions.insert({title: "Debian", distro: "linux-based"})

For multiple insertions, you may follow the syntax provided below. Syntax for multiple insertions:

> db.collection-name.insert([{<document1>}, {<document2>}])

For example, the command written below will add three documents in distributions collection:

> db.distributions.insert([{_id: 1, distro: "Debian-based"}, {_id: 2, distro: "Ubuntu-based"}, {_id: 3, distro: "Linux-based"}])

14: insertMany() “insert multiple documents”

This insert command adds multiple documents in a Mongo collection, and the syntax of this method is the same as of the insert() method.

> db.collection-name.insertMany([{<document1>},{<document>}])

Note: If you forgot to place “[ ]“, then insertMany() will add only one document that is placed at first position.

15: update() “update a document”

To update any document in MongoDB, you have to follow the syntax provided below:

> db.collection-name.update({match}, {update})

To exercise this syntax, we have updated a document that matches “_id: 3” and had set its “distro” field’s value to “Ubuntu-based“:

> db.distributions.update({_id: 3},{$set: {distro: "Ubuntu-based"}})

16: remover() “to remove a document”

The documents inside a Mongo collection can be removed with the help of the remove() command, and you can execute it in the following way:

Note: It is recommended to use the “_id” (as it is always unique) field for the removal of documents because other fields may have redundancy in field values, and there are chances of multiple deletions in such cases.

> db.distributions.remove({_id: 1})

17: find() “to display the content”

The find() command in MongoDB is most useful when retrieving the data from a collection. You can use the find() method in the following way and the command written below will show all the documents inside distributions:

> db.distributions.find()

18: pretty() “get a clear result”

You can get the documents inside the collection in an understandable manner by using pretty() with find() method. For instance, the following command will help to exercise pretty() method on staff collection:

> db.staff.find().pretty()

19: sort() “sort the order of result”

The sorting is quite helpful in getting the content of any collection in the desired order. For instance, the below-mentioned command will sort the documents of staff collection with respect to the name field, and the sorting order is set to descending:

Note: For descending order, you have to pass “-1” with the respective field and “1” for ascending order.

> db.staff.find().sort({name: -1})

MongoDB commands used to handle users

In this section, you will learn to handle commands to create, remove a user from a MongoDB database.

20: createUser() “create new user”

This Mongo-based command creates new users for your MongoDB server. Moroever, the user roles can also be assigned using createUser() command. The command written below will add a user named “linuxuser” and will assign a “readWrite” role to it:

> db.createUser({user: "linuxuser", pwd: "abc", roles: [{role: "readWrite", db:  "linuxhint"}]});

21: show users “to display the users on current database”

You can get the list of users (on a current database) by issuing the following command in your MongoDB shell:

> show users

Or the below-stated command can be executed to get the same result:

> db.getUsers()

22: show roles “to check the roles of each user”

This command can be used to show the roles of the users on several MongoDB databases. In our context, the command written below displays the roles of users:

> show roles

23: dropUser() “to drop a user”

To drop any user from the user’s list, you have to execute the command by specifying the name of the user you want to remove. For instance, the below-mentioned command will drop “linuxuser“:

> db.dropUser("linuxuser")

Conclusion

MongoDB has provided a strong command support mechanism for its users. MongoDB users can perform any database-related operation in an effective manner, and these operations are supported by MongoDB commands. In this guide of the MongoDB series, we have focused on the most useful commands for MongoDB. Here, you will learn to get an understanding of the commands of MongoDB and to apply these commands in the MongoDB shell. Moreover, this is a perfect guide for beginners and the advanced level users may exercise this guide to get good hands-on MongoDB.

About the author

Adnan Shabbir