Mongo DB Complete Cheat Sheet

Tech 9-on
6 min readDec 30, 2021
Mongo db image …

First of all we show the format by which we will go all this information:

  1. Title of the command
>> command
Output

First of all you should install the mongo DB and then try all of these commands..

>> mongo --version
MongoDB shell version v4.4.2
Build Info: {
"version": "4.4.2",
"gitVersion": "15e73dc5738d2278b688f8929aee605fe4279b0e",
"modules": [],
"allocator": "tcmalloc",
"environment": {
"distmod": "windows",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}

Let’s Start Here

Start Mongo at Command Prompt or any shell

>> mongo
MongoDB shell version v4.4.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4e9cfa60-5647-4fba-865f-1d0c17b0ddeb") }
MongoDB server version: 4.4.2
---
The server generated these startup warnings when booting:
2021-12-25T10:59:38.551+05:30: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>

If you are at this location then enjoy Complete mongo now..

Show All Database

>> show dbsadmin   0.000GB
config 0.000GB
local 0.000GB

Create or Switch Database

>> use mydb
switched to db mydb

Show Current Database

>> db
mydb

drop database:- delete the database

>> db.dropDatabase()
{ "ok" : 1 }
>> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
>> use mydb
switched to db mydb

Create Collection

>> db.createCollection('posts')
{ "ok" : 1 }

show Collection

>> show collections
posts

Insert Row

>> db.posts.insert({name:'stupid',tags:'tech'})
WriteResult({ "nInserted" : 1 })

Insert Multiple Row

> db.posts.insertMany([
{
name:’miku’,tags:’fun’,topic:’mongo’},{name:’mr.cool’,tags:’club’,agree:’yes’}
])
{
“acknowledged” : true,
“insertedIds” : [
ObjectId(“61cbe993043263add37a5cd6”),
ObjectId(“61cbe993043263add37a5cd7”)
]
}

insert One

> db.posts.insertOne({name:'miku1',tags:'fun1',topic:'mongo1'})
{
"acknowledged" : true,
"insertedId" : ObjectId("61cbea1b043263add37a5cd8")
}

Difference Between insert, insertOne, insertMany

insert:- db.collection.insert() as mentioned in the documentation inserts a document or documents into a collection and returns a WriteResult object for single inserts and a BulkWriteResult object for bulk inserts.

insertOne :- db.collection.insertOne() as mentioned in the documentation inserts a document into a collection and returns a document.

insertMany:- db.collection.insertMany() inserts multiple documents into a collection and returns a document that looks like this.

Situation Where to use What?

The insert() method is deprecated in major driver so you should use the the .insertOne() method whenever you want to insert a single document into your collection and the .insertMany when you want to insert multiple documents into your collection. Of course this is not mentioned in the documentation but the fact is that nobody really writes an application in the shell. The same thing applies to updateOne, updateMany, deleteOne, deleteMany, findOneAndDelete, findOneAndUpdate and findOneAndReplace.

Get All Rows

>> db.posts.find(){ "_id" : ObjectId("61cbe8e1043263add37a5cd5"), "name" : "stupid", "tags" : "tech" }
{ "_id" : ObjectId("61cbe993043263add37a5cd6"), "name" : "miku", "tags" : "fun", "topic" : "mongo" }
{ "_id" : ObjectId("61cbe993043263add37a5cd7"), "name" : "mr.cool", "tags" : "club", "agree" : "yes" }
{ "_id" : ObjectId("61cbea1b043263add37a5cd8"), "name" : "miku1", "tags" : "fun1", "topic" : "mongo1" }

Get All Row Formatted

> db.posts.find().pretty(){
"_id" : ObjectId("61cbe8e1043263add37a5cd5"),
"name" : "stupid",
"tags" : "tech"
}
{
"_id" : ObjectId("61cbe993043263add37a5cd6"),
"name" : "miku",
"tags" : "fun",
"topic" : "mongo"
}
{
"_id" : ObjectId("61cbe993043263add37a5cd7"),
"name" : "mr.cool",
"tags" : "club",
"agree" : "yes"
}
{
"_id" : ObjectId("61cbea1b043263add37a5cd8"),
"name" : "miku1",
"tags" : "fun1",
"topic" : "mongo1"
}

Sort Rows

title: 1 => for accending

title:-1 => for decending

>> db.posts.find().sort({name:1}){ "_id" : ObjectId("61cbe993043263add37a5cd6"), "name" : "miku", "tags" : "fun", "topic" : "mongo" }
{ "_id" : ObjectId("61cbea1b043263add37a5cd8"), "name" : "miku1", "tags" : "fun1", "topic" : "mongo1" }
{ "_id" : ObjectId("61cbe993043263add37a5cd7"), "name" : "mr.cool", "tags" : "club", "agree" : "yes" }
{ "_id" : ObjectId("61cbe8e1043263add37a5cd5"), "name" : "stupid", "tags" : "tech" }
>> db.posts.find().sort({name:-1}){ "_id" : ObjectId("61cbe8e1043263add37a5cd5"), "name" : "stupid", "tags" : "tech" }
{ "_id" : ObjectId("61cbe993043263add37a5cd7"), "name" : "mr.cool", "tags" : "club", "agree" : "yes" }
{ "_id" : ObjectId("61cbea1b043263add37a5cd8"), "name" : "miku1", "tags" : "fun1", "topic" : "mongo1" }
{ "_id" : ObjectId("61cbe993043263add37a5cd6"), "name" : "miku", "tags" : "fun", "topic" : "mongo" }

Count Rows

>> db.posts.find().count()
4
>> db.posts.find({name:'miku'}).count()
1

Limit Rows

>> db.posts.find().limit(2)
{ "_id" : ObjectId("61cbe8e1043263add37a5cd5"), "name" : "stupid", "tags" : "tech" }
{ "_id" : ObjectId("61cbe993043263add37a5cd6"), "name" : "miku", "tags" : "fun", "topic" : "mongo" }

Chaining

>> db.posts.find().limit(2).sort({name:1}).pretty()
{
"_id" : ObjectId("61cbe993043263add37a5cd6"),
"name" : "miku",
"tags" : "fun",
"topic" : "mongo"
}
{
"_id" : ObjectId("61cbea1b043263add37a5cd8"),
"name" : "miku1",
"tags" : "fun1",
"topic" : "mongo1"
}

ForEach

>> db.posts.find().forEach(function(doc){print(doc.name)})
stupid
miku
mr.cool
miku1

Remove all the documents

>> db.posts.remove({})
WriteResult({ "nRemoved" : 4})

For further operation lets create some documents:-

>> db.posts.insertMany([
{title1:"info1",title2:'info2',title3: 'info3'},{title1:'info1',title2:'info4'{title1:'info2',title4:'info4'}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("61cbfb7b043263add37a5cd9"),
ObjectId("61cbfb7b043263add37a5cda"),
ObjectId("61cbfb7b043263add37a5cdb")
]
}
>> db.posts.find().pretty()
{
"_id" : ObjectId("61cbfb7b043263add37a5cd9"),
"title1" : "info1",
"title2" : "info2",
"title3" : "info3"
}
{
"_id" : ObjectId("61cbfb7b043263add37a5cda"),
"title1" : "info1",
"title2" : "info4"
}
{
"_id" : ObjectId("61cbfb7b043263add37a5cdb"),
"title1" : "info2",
"title4" : "info4"
}

Remove Single Row

>> db.posts.remove({title1:'info1'},true)
WriteResult({ "nRemoved" : 1 })

add some more rows in collections

> db.posts.insertMany([
{title1:'info1','title2':'hello'},{tittle1:'newtitle',title2:'nice'}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("61cbfdd1043263add37a5cdc"),
ObjectId("61cbfdd1043263add37a5cdd")
]
}

Remove All matches Row

>> db.posts.remove({title1:'info1'})
WriteResult({ "nRemoved" : 2 })
>> db.posts.find()
{ "_id" : ObjectId("61cbfb7b043263add37a5cdb"), "title1" : "info2", "title4" : "info4" }
{ "_id" : ObjectId("61cbfdd1043263add37a5cdd"), "tittle1" : "newtitle", "title2" : "nice" }
>>db.posts.remove({})
WriteResult({ "nRemoved" : 2 })
>> db.posts.insertMany([{a:1,b:2,c:3},{a:1,b:2,d:4},{a:1,b:2,c:5,e:4,{a:1,b:4,c:3},{a:1,b:2,c:4}}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("61cc11c2043263add37a5cde"),
ObjectId("61cc11c2043263add37a5cdf"),
ObjectId("61cc11c2043263add37a5ce0"),
ObjectId("61cc1265043263add37a5ce1"),
ObjectId("61cc1265043263add37a5ce2") ]
}

Find all

syntax: -> db.posts.find({condition},{what to show or not})

condition: find row who follow the condition like a:1

what to show or not: 0-> not show, 1-> only show

>> db.posts.find({})
{ "_id" : ObjectId("61cc11c2043263add37a5cde"), "a" : 1, "b" : 2, "c" : 3 }
{ "_id" : ObjectId("61cc11c2043263add37a5cdf"), "a" : 1, "b" : 2, "d" : 4 }
{ "_id" : ObjectId("61cc11c2043263add37a5ce0"), "a" : 1, "b" : 2, "c" : 5, "e" : 4 }
{ "_id" : ObjectId("61cc1265043263add37a5ce1"), "a" : 1, "b" : 4, "c" : 3 }
{ "_id" : ObjectId("61cc1265043263add37a5ce2"), "a" : 1, "b" : 2, "c" : 4 }

Find all data without id

>> db.posts.find({},{_id:0})
{ "a" : 1, "b" : 2, "c" : 3 }
{ "a" : 1, "b" : 2, "d" : 4 }
{ "a" : 1, "b" : 2, "c" : 5, "e" : 4 }
{ "a" : 1, "b" : 4, "c" : 3 }
{ "a" : 1, "b" : 2, "c" : 4 }

Find all data with a specific field

>> db.posts.find({b:2},{a:1,b:1,_id:0})
{ "a" : 1, "b" : 2 }
{ "a" : 1, "b" : 2 }
{ "a" : 1, "b" : 2 }
{ "a" : 1, "b" : 2 }

Normal find with condition

>> db.posts.find({b:2})
{ "_id" : ObjectId("61cc11c2043263add37a5cde"), "a" : 1, "b" : 2, "c" : 3 }
{ "_id" : ObjectId("61cc11c2043263add37a5cdf"), "a" : 1, "b" : 2, "d" : 4 }
{ "_id" : ObjectId("61cc11c2043263add37a5ce0"), "a" : 1, "b" : 2, "c" : 5, "e" : 4 }
{ "_id" : ObjectId("61cc1265043263add37a5ce2"), "a" : 1, "b" : 2, "c" : 4 }

Special Condition Find

$gt => greater than

$gte => greater than equal to

$lt => less than

$lte => less than equal to

>> db.posts.find({b:{$gt:2}},{_id:0})
{ "a" : 1, "b" : 4, "c" : 3 }
>> db.posts.find({"b":{$lte:2}},{_id:0})
{ "a" : 1, "b" : 2, "c" : 3 }
{ "a" : 1, "b" : 2, "d" : 4 }
{ "a" : 1, "b" : 2, "c" : 5, "e" : 4 }
{ "a" : 1, "b" : 2, "c" : 4 }

Update:-

some terminology:- upsert — update and insert

update:- first matched document update

update with upsert -> update if document matched else insert document

>> db.posts.update({"a":1},{a:2,b:4})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>> > db.posts.update({"a":6},{a:2,b:4},{upsert:true})
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("61cd6436f72f6f1b647d0cb7")
})

update Specific Field

// without upsert
>> db.posts.update({b:5},{$set:{a:44,e:99}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
// with upsert
>> db.posts.update({b:55},{$set:{a:45}},{upsert:true})
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("61cd662cf72f6f1b647d0cd2")
})

Delete row

remove - delete all matching rows

>> db.posts.remove({a:1})
WriteResult({ "nRemoved" : 3 })
// delete all the rows>>db.posts.remove({})
WriteResult({ "nRemoved" : 9})

deleteOne and deleteMany

>> db.posts.deleteOne({a:2})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.posts.deleteMany({a:2})
{ "acknowledged" : true, "deletedCount" : 3 }

All above commands are basics of mongo db. I also publish some more tricky topics and commands, which help you to pro your knowledge. So Don’t forget to checkout my other articles.

subscribe: https://www.youtube.com/channel/UCff4MIUUsgENE4aqa8DCAAA

Thanks……………………………………………………..By Tech 9-on

--

--

Tech 9-on

I am a full stack web developer. I am really passionate to work in web technologies