MongoDB and Crud Operations


What is MongoDB?


MongoDB, also known as Mongo, is an open-source document database used in many modern web applications. It is classified as a NoSQL database because it does not rely on a traditional table-based relational database structure.

Instead, Mongo uses JSON-like documents with dynamic schemas. This means that, unlike relational databases, MongoDB does not require a predefined schema before you add data to a database. You can alter the schema at any time and as often as is necessary without having to set up a new database with an updated schema.

   MongoDB Crud Operations

  • Create Operations
  • Read Operations
  • Update Operations
  • Delete Operations


Create Operation

Insert /add One Document 

db.getCollection('Student').insertOne(


{       "name": "John", 

        "dateOfBirth": "1990-01-01T00:00:00Z", 

        "subjects": ["Application frameworks", "Computer architecture"]

    })


 Inserting/Adding 2 documents to the same collection. 

db.getCollection('Student').insertMany([

{   "name": "Smith",

    "dateOfBirth": "1990-01-15T00:00:00Z", 

    "subjects": ["Application frameworks", "Computer architecture"], 

    "isActive": true 

},

{

   "name": "Jane",

    "dateOfBirth": "1990-02-15T00:00:00Z", 

    "subjects": ["Application frameworks", "Computer architecture"],  

    "isActive": false 

}

] )


Read Operation

Find the document by ‘name’. 

db.getCollection('Student').find({"name":"John"})


 Find the document by ‘_id’. 

db.getCollection('Student').find({"_id":ObjectId("6043906579f5ccfbfb9649b7")})


Update Operation

Update the Document

Add ‘Distributed Computing’ to the subjects list. 

db.getCollection('Student').updateOne(

{

    "name":"John"

},

{

  $push:{"subjects": "Distributed Computing"}

}

)


Find And Update the Document

Find the document with the name ‘Smith’ and isActive flag is true and add Distributed computing to subjects. 

db.getCollection('Student').updateOne(

{

    "name":"Smith",

    "isActive":true

},

{

  $push:{"subjects": "‘Distributed Computing"}      

}

)

Update the first document ‘isActive’ to false. 

db.getCollection('Student').updateOne(

{

 

    "name": "John"

},

{

  $push:{"isActive": false}      

}

)

Note

Even Though earlier We doesn't have isActive Document in Object1 "name": "John" after we update it by giving "isActive":false Document will be updated by adding new Document "isActive":false

Delete Operation

Removing the document.

db.getCollection('Student').find({})


See more MongoDB And Related Exercises in My GitHub Repository

https://github.com/nushkymohamed/APLICATION-FRAMEWORKS-LAB/blob/main/LAB%20MONGODB.docx



Comments

Post a Comment

Popular posts from this blog

Node.js

Getting Started With The React Hooks API

What is ReactJS: Introduction To React and Its Features