DEV Community

Cover image for Everything you should know about MongoDB

Everything you should know about MongoDB

Watch Full Course of MongoDB on YouTube

MongoDB : Introduction

MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term โ€˜NoSQLโ€™ means โ€˜non-relationalโ€™. It means that MongoDB isnโ€™t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format).

*MongoDB records are called documents and they look very much like objects as they use Key-pair. *

A simple MongoDB document Structure:

{
โ€˜titleโ€™:'MongoDb World',
โ€˜ratingโ€™: 10,
โ€˜durationโ€™: 200
โ€˜Youtubeโ€™: 'Bitfumes'
}
// It is much easy to work with this if you are using JavaScript because 
// documents are very much like JSON or JavaScript objects. 
// Secondly, it allows us to store nested documents within a document.
{
โ€˜titleโ€™:'MongoDb World',
โ€˜ratingโ€™: 9,
โ€˜durationโ€™: 400,
โ€˜authorโ€™:{
  โ€˜firstnameโ€™:'โ€ฆ',
  โ€˜lastnameโ€™:'โ€ฆ'
}
}
Enter fullscreen mode Exit fullscreen mode

Q) Why MongoDB?

-> There are four major reasons:

1. Flexibility:
MongoDB uses documents that can contain sub-documents in complex hierarchies making it expressive and flexible.

2. Flexible Query Model:
The user can selectively index some parts of each document or a query based on regular expressions, ranges, or attribute values, and have as many properties per object as needed by the application layer.

3. Native Aggregation:
Native aggregation allows users to extract and transform data from the database. The data can either be loaded into a new format or exported to other data sources.

4. Schema-less model:
Applications get the power and responsibility to interpret different properties found in a collection's documents.

Feature Of MongoDB

Image description

Q)But What is the difference between relational and Non-Relational Databases?

relation vs non.png

Structural representation of MongoDB

collect.png

we have a MongoDB database now inside you can have one collection that collection can have a single document it can have more than two or three any number of documents. So collection to the document now you can also have more than one collection and similar to that we can have more than one document inside the collection so the hierarchy is something like database collection document and inside the document, we should have the fields.

{
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Alan", last: "Turing" },
               birth: new Date('Jun 23, 1912'),
               death: new Date('Jun 07, 1954'),
               contribs: [ "Turing machine", "Turing test", "Turingery" ],
               views : NumberLong(1250000)
            }
Enter fullscreen mode Exit fullscreen mode

The above fields have the following data types:

  1. _id holds an ObjectId(Which is Uniquely Generated by MongoDB).
  2. name holds an embedded document(document inside the document) that contains the fields first and last.
  3. birth and death hold values of the Date type.
  4. contribs holds an array of strings.
  5. views holds a value of the NumberLong type.

mongodb1.png

Let's see How to Install MongoDB on your machine

Go to the Install section on the MongoDB website.
use the brew to install the community edition but with the brew the community edition you also get the shell or I can call it mongoose but with windows installation, if you install this MongoDB service you can directly download this MongoDB MSI file and then open it and use the wizard to install it that's easy but you have to install the mongoose explicitly the thing which is going to help you to access the MongoDB from your shell from your command prompt.

Or you can watch Installation Part Here

Create a New Database and Collection

Watch here

To run commands in mongosh, you must first connect to a MongoDB deployment.

To display the database you are using, type db :

To switch databases, use helper, as in the following example:

use <Database_Name>

Enter fullscreen mode Exit fullscreen mode

To create a new database, issue the use command with the database that you would like to create. For example, the following commands create both the database myNewDatabase and the collection myCollection using the insertOne() operation:

use myNewDatabase
db.myCollection.insertOne( { x: 1 } );
Enter fullscreen mode Exit fullscreen mode

If a collection does not exist, MongoDB creates the collection when you first store data for that collection.This is the special power of MongoDB

power.webp

How to Perform CRUD Operations in MongoDB

Q) What is CRUD?
-> CRUD operation means creating, reading, updating, and deleting documents.

Insert Documents in MongoDB

Watch here

The MongoDB shell provides the following methods to insert documents into a collection:

  • To insert a single document, use db.collection.insertOne().
  • To insert multiple documents, use db.collection.insertMany().

If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.

//Example of InsertOne()

use sample_mflix
db.movies.insertOne(
  {
    title: "The Favourite",
    genres: [ "Drama", "History" ],
    year: 2018,
    directors: [ "Yorgos Lanthimos" ],
    type: "movie"
  }
)
Enter fullscreen mode Exit fullscreen mode
//Example of insertMany()

use sample_mflix
db.movies.insertMany([
   {
      title: "Jurassic World: Fallen Kingdom",
      genres: [ "Action", "Sci-Fi" ],
      year: 2018,
      directors: [ "J. A. Bayona" ],
      type: "movie"
    },
    {
      title: "Titanic",
      genres: [ "Comedy", "Action" ],
      year: 2019,
      directors: [ "Jeff Tomsic" ],
      type: "movie"
    }
])
Enter fullscreen mode Exit fullscreen mode

Query(Find) Documents in MongoDB

Watch here

Use the db.collection.find() method in the MongoDB Shell to query(Find) documents in a collection.

Read All Documents in a Collection

To read all documents in the collection, pass an empty document as the query filter parameter to the find method.

db.movies.find()
Enter fullscreen mode Exit fullscreen mode

Specify Equality Condition

To select documents that match an equality condition, specify the condition as a (field):(value) pair in the query filter document.

To return all movies where the title equals Titanic from the sample_mflix.movies collection

use sample_mflix
db.movies.find( { "title": "Titanic" } )

Enter fullscreen mode Exit fullscreen mode

Specify Conditions Using Query Operators

Use query operators in a query filter document to perform more complex comparisons and evaluations. Query operators in a query filter document have the following form:

{ <field1>: { <operator1>: <value1> }, ... }
Enter fullscreen mode Exit fullscreen mode

To return all movies from the sample_mflix.movies collection which are either released 2018 or 2019:

use sample_mflix
db.movies.find( { rated: { $in: [ "2018", "2019" ] } } )
Enter fullscreen mode Exit fullscreen mode

Update Documents in MongoDB

Watch here

The MongoDB shell provides the following methods to update documents in a collection:

  • To update a single document, use db.collection.updateOne().
  • To update multiple documents, use db.collection.updateMany().
  • To replace a document, use db.collection.replaceOne().

Update Operator Syntax

To update a document, MongoDB provides update operators, such as $set, to modify field values.
To use the update operators, pass to the update methods an update document of the form:

{
  <update operator>: { <field1>: <value1>, ... },
  <update operator>: { <field2>: <value2>, ... },
  ...
}
Enter fullscreen mode Exit fullscreen mode

Some update operators, such as $set, create the field if the field does not exist.

Update a Single Document

Use the db.collection.updateOne() method to update the first document that matches a specified filter.

//To update the first document in the sample_mflix.movies collection where title equals "Tag":
use sample_mflix

db.movies.updateOne( { title: "Tag" },
{
  $set: {
    plot: "One month every year, five highly competitive friends
           hit the ground running for a no-holds-barred game of tag"
  }
  { $currentDate: { lastUpdated: true } }
})
Enter fullscreen mode Exit fullscreen mode

Update Multiple Documents

Use the db.collection.updateMany() to update all documents that match a specified filter.

//To update all documents in the sample_airbnb.listingsAndReviews 
//collection to update where security_deposit is less than 100:

use sample_airbnb

db.listingsAndReviews.updateMany(
  { security_deposit: { $lt: 100 } },
  {
    $set: { security_deposit: 100, minimum_nights: 1 }
  }
)
Enter fullscreen mode Exit fullscreen mode

Replace a Document

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne().

//To replace the first document from the sample_analytics.accounts
// collection where account_id: 371138:
db.accounts.replaceOne(
  { account_id: 371138 },
  { account_id: 893421, limit: 5000, products: [ "Investment", "Brokerage" ] }
)
Enter fullscreen mode Exit fullscreen mode

Delete Documents

Watch here

The MongoDB shell provides the following methods to delete documents from a collection:

  • To delete multiple documents, use db.collection.deleteMany().
  • To delete a single document, use db.collection.deleteOne().

Delete All Documents

To delete all documents from a collection, pass an empty filter document {} to the db.collection.deleteMany() method.

//To delete all documents from the sample_mflix.movies collection:

use sample_mflix
db.movies.deleteMany({})
Enter fullscreen mode Exit fullscreen mode

Delete Only One Document that Matches a Condition

To delete at most a single document that matches a specified filter (even though multiple documents may match the specified filter) use the db.collection.deleteOne() method.

//To delete the first document from the sample_mflix.movies collection 
//where the director array contains "Jeff Tomsic":

use sample_mflix
db.movies.deleteOne( { directors: "Jeff Tomsic" } )
Enter fullscreen mode Exit fullscreen mode

That's All you need to know about MongoDB

finally.webp

So Far We have learned a lot. Do ask questions for clarifications and make corrections & suggestions, I expect them. That is all from my end, please share your views in the comment section, and thanks for reading it. Check out my other article Here. Also, Subscribe to my newsletter. Follow me on Socials. Happy Learning and Coding

200w (1).webp

Subscribe To My YouTube channel

Follow me on Twitter

THANK YOU SO MUCH FOR YOUR TIME

Top comments (1)

Collapse
 
chendo19 profile image
Rosendo Rodriguez

Great job, as always!