Most Common MongoDB Commands for MongoDB Beginners [2020]

Logging with MongoDB

The following command applies to logging in with MongoDB.

mongo -u <username> -p <password> –authenticationDatabase <db_name>

Note: Users must have the right credentials and database name for access.

Create a Database and Selecting the Database to work with 

In MongoDB, the ‘use’ command is the first step to create a new database. 

Syntax:

use db_name

On execution, this command will create a new database for a specific name. In case there is a database with a specific name, then it will return with the existing database.

The same ‘use’ command is also used for selecting a database and start working with.  

Example:

Suppose you are starting a new education project with the database ‘edudb’. Then the command would be:

>use edudb

Switched to db edudb

Read: MongoDB Real World Use Cases: Advantages & Top Companies

Check Current Database

You can also check the current database with the command db as:

>db

Edudb

You need to have at least one file or document in the database to show in the overall list. You can do this by using the insert command easily.

Syntax:

> db.file.insert({“name”:”classes”})

Show all current databases

You can use the following commands to check the present database with show dbs as:

>show dbs

local          0.53443GB

test           0.12332GB

edudb      0.02423GB

In MongoDB, the test is present as the default database. All the collections by default are stored in the test only. 

You can use the MongoDB command interface to manage tasks related to non-CRUD operations. The interface empowers users to fetch precise information from the server, replicating current scenarios, and run specific map-reduce tasks.

There are also specific commands to run in the current and admin database.

For current database in MondDB, use the following db.runCommand():

db.runCommand( { <command> } )

For admin database, use the following db.adminCommand():

db. adminCommand ( { <command> } )

For Creating a Collection, the following command:

db.createCollection(“collectionName”);

 For inserting a document in the Collection:

//

// For inserting a single document in the collection

//

db.<collectionName>.insert({field1: “value”, field2: “value”})

//

// For inserting multiple documents in the collection

//

db.<collectionName>.insert([{field1: “value1”}, {field1: “value2”}])

db.<collectionName>.insertMany([{field1: “value1”}, {field1: “value2”}])

To Save and Update document

Here ‘save’ command can do both functions insert an entirely new document or update an existing document.

db.<collectionName>.save({“_id”: new ObjectId(“jhgsdjhgdsf”), field1: “value”, field2: “value”});

Note: If there is a matching document ID, then it updates; otherwise, a new document is then created.

 Listing the Users, Roles, and Collections

These commands list the number of users, their roles, and collections.

//

// Command to list all the collections from the current database

//

show collections;

db.getCollectionNames();

//

// Command to all the users from the current database

//

show users;

db.getUsers();

//

// Command to list all the user roles

//

show roles 

To Display Collection records 

  //

// Command to retrieve all records

//

db.<collectionName>.find();

//

// This command fetches the first 10 results;

//

db.<collectionName>.find().limit(10);

//

// This command retrieves the records by id

//

db.<collectionName>.find({“_id”: ObjectId(“someid”)});

//

// This command fetches the value from a particular collection attribute with an object and assigned value of  0 or 1.

//

db.<collectionName>.find({“_id”: ObjectId(“someid”)}, {field1: 1, field2: 1});

db.<collectionName>.find({“_id”: ObjectId(“someid”)}, {field1: 0}); // Exclude field1

//

// This command checks the Collection count in a database

//

db.<collectionName>.count();

 

 For Administrative Commands

This command allows information about collection details with total size, storage, and multiple statistics.

//

// This command retrieves the collection statistics

//

db.<collectionName>.stats()

db.printCollectionStats()

//

// // This command retrieves the Latency statistics for reading and writes and a specific number of operations

//

db.<collectionName>.latencyStats()

//

// This command retrieves specific collection size for indexes and data

//

db.<collectionName>.dataSize() // fetches the Size of the collection

db.<collectionName>.storageSize() // fetches the total size of document stored

db.<collectionName>.totalSize() // fetches the total size in bytes for both collection data and indexes

db.<collectionName>.totalIndexSize() // fetches the total size of all indexes in the collection

 For logging out from the database:

db.logout()

There are different types of commands that you can use in MongoDB, starting with:

User commands

Database Operations

1. User Commands

Aggregation Commands

Name Description
aggregate Command to perform aggregation tasks in a group.
count Command to count the specific number of documents.
distinct Command to display distinct value for a specific key in a collection.
mapReduce Command to perform map-reduce task aggregation in large data sets.

 Geospatial Commands

Name Description
geoSearch A command that performs a geospatial query through MongoDB haystack index function.

 Query and Write operations commands

Name Description
delete Command to delete one or multiple documents.
find Command to select single or multiple documents in a view.
insert Command to insert one or multiple documents in a view.
update Command to update one or multiple documents.

Query Plan Cache Commands 

Name Description
planCacheClear Command to remove cached query plans from a collection.
planCacheClearFilters Command that clears index filters from a collection.
planCacheListFilters Command that lists index filters from a collection.
planCacheSetFilter Command that sets an index filter from a collection.

2. Database Operations

Authentication Problems

Name Description
authenticate A command that starts an authenticated session after verifying a username and password.
getnonce Command to generate a one-time password for authentication.
logout Command to terminate the given authenticated session.

User Management Commands

Name Description
createUser Command to create a new user.
dropUser Command to remove a specific user.
updateUser Command to update specific user data.
usersInfo Command to retrieve information from a specific single or multiple users.

Role Management Commands

Name Description
createRole Command to build a specific user role and privilege.
dropRole Command to delete a specific user-defined role from the database.
updateRole Command that updates a specific user-defined role.

 Replication Commands

Name Description
applyOps A command that adds oplog entries with the present data set.
isMaster A command that displays information for the specific user in the present replica set to check if it is the master or not.
replSetInitiate Command that initializes a specific new replica set.

 Sharding Commands

Name Description
addShard A command that adds a new shard or sharded cluster.
listShards A command that returns a list of pre-configured shards.
removeShard A command that removes the particular shard from the cluster.
   

 Session Commands

Name Description
abortTransaction Command to abort the transaction.
endSessions Command to expire sessions before the timeout.
killAllSessions Command to kill all sessions
refreshSessions Command to refresh idle sessions.
startSession Command to start a new session.

 Administrative Commands

Name Description
clean A command that represents an internal namespace.
create Command to create a collection or a specific view.
drop Command to remove a specific collection from the current database.
reIndex Command that rebuilds all indexes for a particular collection.
shutdown Command to shut down the mongos or mongod process.

 Free Monitoring Commands

Name Description
setFreeMonitoring It allows users to enable or disable free monitoring within the runtime.

 Auditing Commands

Name Description
logApplicationMessage Commands add or post a customized message with the current audit log.

Command Responses

On every command execution, MongoDB retrieves a response with a specific field:

Field Description
ok An indication that command was a success (1) or a failure (0).
operationtime This represents the specific time for performing operations in MongoDB with a timestamp from the oplog entry.

In case the operation does not operate, then it does not generate any oplog entry. Then the operation time returns;

local: from the most recent entry through the oplog.

And for a majority and linearizable reads, the timestamp from the recent majority-acknowledged entry through the oplog.  

$clusterTime That defines the logical time for ordering a specific operation.

Checkout: CRUD Operations in MongoDB

What Next?

If you are interested to know more about Big Data, check out our PG Diploma in Software Development Specialization in Big Data program which is designed for working professionals and provides 7+ case studies & projects, covers 14 programming languages & tools, practical hands-on workshops, more than 400 hours of rigorous learning & job placement assistance with top firms.

Lead the Data Driven Technological Revolution

400+ HOURS OF LEARNING. 14 LANGUAGES & TOOLS. IIIT-B ALUMNI STATUS.
Enroll Today

Leave a comment

Your email address will not be published. Required fields are marked *

×