Commands for Mongodb(container)

Myglobin
3 min readJul 7, 2021

In this blog, I’m giving some useful commands for mongodb. Here, I’m running the mongodb as docker container. For creating a docker container for mongodb, follow below commands:

docker pull mongo
docker run --name mongodb -d mongo
Output from above commands

Here, mongodbis the name I gave for the container. To see whether the container is up, use below command:

docker ps
Output for docker ps command

The following command line will give you a bash shell inside your mongodb container:

docker exec -it mongodb bash

This command helps to run commands inside the mongodb container. The highlighted text in below figure is the container ID and ‘root’ is the user.

Use command mongo for mongo shell.

shell

Below command gives the database list:

show dbs

By default, mongodb have these dbs:

Default DBs

There is no “create” command in the MongoDB shell. We just use use users command to create a database named ‘user’. The command db gives the current db name and to switch db, use <db_name> . When you use show dbs , ‘users’ will not be listed. Until we store data to the new db, the db will not be listed.

Let’s insert data to the db. The equivalent of ‘table’ in RDBS is ‘collection’; ‘row’ is ‘document’; ‘column’ is ‘field’.

db.users.insert({user_id: 1, name: 'Jane Doe', role: 'admin'})

This will create collections called ‘users’ and data will be inserted. Another way to create a collection is db.createCollection("users") . We can also insert multiple documents using the command insertMany() .

db.users.insertMany([{user_id: 1,name: 'Jane Doe', role: 'admin'},{user_id: 2, name: 'John Doe', role: 'admin'}])

To create a primary key, use createIndex() method.

db.users.createIndex( { "user_id": 1 }, { unique: true } )

Command below will show all the collections in the db.

show collections

The command below will get the data from the database:

The pretty() function helps to display the result in a easy, readable format.

If you try to insert the data with same user_id after creating the index, we get error saying duplicate key error as shown:

Now, if we need the table properties or details, use below command:

db.getCollectionInfos()

Result:

To update a document we can use the update() function. The format for the update() method is db.users.update(<filter>, <update>, <options>) . Below is an example:

db.users.update({role: 'admin'}, {$set: {role: 'tester'}})

The above command will update the first document only. If we want to update all the documents which satisfy {role: 'admin'}, we should use {multi: true} .

db.users.update({role: 'admin'}, {$set: {role: 'tester'}},{multi: true})

Depending on the criteria, the update is executed, i.e. {role: 'admin'} can be {user_id: 1} also.

To drop a collection, use

db.users.drop()

These are few basic commands for mongodb.

--

--