Swastik Yadav

S Y

Navigate back to the homepage

MongoDB Introduction and CheatSheet

Swastik Yadav
August 6th, 2021 · 1 min read

Hello World,

In this post we will explore some basic commands of mongoDB. MongoDB is a NO SQL database.

With NO SQL databases like mongoDB we store our data in collections of documents. Documents are very similar to JSON objects, they are BSON which is similar to JSON with some additional datatypes.

MongoDB is very scalable, it has built in replication and sharding (a method for distributing data across multiple machines). It scales horizontally.

With mongoDB we don’t have to map our data structure beforehand like we do in relational SQL databases.

Installation

There are two major ways to use mongoDB. One is to install mongo in your operating sytem and second is to use mongoDB Atlas a cloud database service. Atlas is preffered over the first one.

Here is Atlas setup tutorial: https://dev.to/dalalrohit/how-to-connect-to-mongodb-atlas-using-node-js-k9i

MongoDB CheatSheet

Now let’s see the most commonly used mongoDB commands.

Show All Databases

1show dbs

Show Current Database

1db

Create Or Switch Database

Switch to the database named acme, or create new database if already does not exist.

1use acme

Drop

Drop the current database.

1db.dropDatabase()

Create Collection

1db.createCollection('posts')

Show Collections

1show collections

Insert Row

1db.posts.insert({
2 title: 'Post One',
3 body: 'Body of post one',
4 category: 'News',
5 tags: ['news', 'events'],
6 user: {
7 name: 'John Doe',
8 status: 'author'
9 },
10 date: Date()
11})

Insert Multiple Rows

1db.posts.insertMany([
2 {
3 title: 'Post Two',
4 body: 'Body of post two',
5 category: 'Technology',
6 date: Date()
7 },
8 {
9 title: 'Post Three',
10 body: 'Body of post three',
11 category: 'News',
12 date: Date()
13 },
14 {
15 title: 'Post Four',
16 body: 'Body of post three',
17 category: 'Entertainment',
18 date: Date()
19 }
20])

Get All Rows

1db.posts.find()

Get All Rows Formatted

1db.posts.find().pretty()

Find Rows

1db.posts.find({ category: 'News' })

Sort Rows

1# asc
2db.posts.find().sort({ title: 1 }).pretty()
3# desc
4db.posts.find().sort({ title: -1 }).pretty()

Count Rows

1db.posts.find().count()
2db.posts.find({ category: 'news' }).count()

Limit Rows

1db.posts.find().limit(2).pretty()

Chaining

1db.posts.find().limit(2).sort({ title: 1 }).pretty()

Foreach

1db.posts.find().forEach(function(doc) {
2 print("Blog Post: " + doc.title)
3})

Find One Row

1db.posts.findOne({ category: 'News' })

Find Specific Fields

1db.posts.find({ title: 'Post One' }, {
2 title: 1,
3 author: 1
4})

Update Row

1db.posts.update({ title: 'Post Two' },
2{
3 title: 'Post Two',
4 body: 'New body for post 2',
5 date: Date()
6},
7{
8 upsert: true
9})

upsert: true creates a new post if the specified post is not found.

Update Specific Field

1db.posts.update({ title: 'Post Two' },
2{
3 $set: {
4 body: 'Body for post 2',
5 category: 'Technology'
6 }
7})

Increment Field (\$inc)

1db.posts.update({ title: 'Post Two' },
2{
3 $inc: {
4 likes: 5
5 }
6})

Rename Field

1db.posts.update({ title: 'Post Two' },
2{
3 $rename: {
4 likes: 'views'
5 }
6})

Delete Row

1db.posts.remove({ title: 'Post Four' })

Sub-Documents

1db.posts.update({ title: 'Post One' },
2{
3 $set: {
4 comments: [
5 {
6 body: 'Comment One',
7 user: 'Mary Williams',
8 date: Date()
9 },
10 {
11 body: 'Comment Two',
12 user: 'Harry White',
13 date: Date()
14 }
15 ]
16 }
17})

Find By Element in Array (\$elemMatch)

1db.posts.find({
2 comments: {
3 $elemMatch: {
4 user: 'Mary Williams'
5 }
6 }
7 }
8)

Add Index

1db.posts.createIndex({ title: 'text' })
1db.posts.find({
2 $text: {
3 $search: "\"Post O\""
4 }
5})

Greater & Less Than

1db.posts.find({ views: { $gt: 2 } })
2db.posts.find({ views: { $gte: 7 } })
3db.posts.find({ views: { $lt: 7 } })
4db.posts.find({ views: { $lte: 7 } })

That’s it for this post, if you found this post helpful, please do share and stay tuned by subscribing to my newsletter below.

Thank You!

More articles from Swastik Yadav

NodeJS - JavaScript powering the backend

Introduction to NodeJS. NodeJS is a JavaScript run time environment. It is the way to run JavaScript outside the browser.

July 30th, 2021 · 2 min read

Intro to object oriented programming in JavaScript

Introduction to object oriented programming. Learn how to create and work with objects.

July 23rd, 2021 · 3 min read

DiaryOfADev, Success stories of underdog developers.

Every week we share an underdog developer's story and a deep dive into a programming concept.

© 2021–2024 Swastik Yadav
Link to $https://github.com/SwastikyadavLink to $https://www.linkedin.com/in/swastikyadav/