DEV Community

Cover image for Building a Solid Foundation: Getting Started with MongoDB and NoSQL for Beginners
Laxit Shah
Laxit Shah

Posted on • Updated on

Building a Solid Foundation: Getting Started with MongoDB and NoSQL for Beginners

->MongoDB is a popular open-source, NoSQL database management system designed for scalability, flexibility, and ease of use.
It uses a document-oriented data model, meaning data is stored in flexible, JSON-like documents called BSON (Binary JSON),
allowing for dynamic schemas.

->In MongoDB, data is organized into collections, which are analogous to tables in relational databases.
Each document within a collection can have a different structure, providing flexibility for evolving data requirements.
MongoDB supports a wide range of data types, including strings, numbers, arrays, and nested documents.

->Database:

->a container that holds collections of documents
Enter fullscreen mode Exit fullscreen mode

->Collections:

->Grouping of Documents 
->Also called as table 
Enter fullscreen mode Exit fullscreen mode

->Documents:

    ->A record inside a Collections
    ->Also called as row
    ->It is a JSON Object
Enter fullscreen mode Exit fullscreen mode

->Field:

    ->A  pair of key-value inside a document
    ->Also called as column
    ->It contains numbers,string,boolean,json object as well as arrays.
Enter fullscreen mode Exit fullscreen mode

->_id:

->In MongoDB, the _id field is a special field that uniquely identifies each document within a collection.
    It acts as the primary key for the document and is automatically created by MongoDB when a document 
    is inserted if an _id field is not explicitly provided.When inserting a document without specifying an _id, 
    MongoDB generates a unique ObjectId value for the _id field. You can also explicitly set a custom value for _id
    if desired, as long as it is unique within the collection.
Enter fullscreen mode Exit fullscreen mode

->To use MongoDB:

->command:mongosh
Enter fullscreen mode Exit fullscreen mode

->To Show Database

->command:show dbs
Enter fullscreen mode Exit fullscreen mode

->To Delete Database:

 ->command:db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

->Switch to Database or create a new Database

->command:use nameofdbs
Enter fullscreen mode Exit fullscreen mode

->Collections:

->Collections are tables in database
->command:show collections
Enter fullscreen mode Exit fullscreen mode

->Delete Collection

->db.student.drop()
Enter fullscreen mode Exit fullscreen mode

->To exit mongodb:

->command:exit
Enter fullscreen mode Exit fullscreen mode

->Question>Why do we write db ahead of every command?

ans>In MongoDB, the db object refers to the current database context. When executing commands or operations, 
it is necessary to specify the database you want to interact with. By prefixing the commands with db, 
you indicate that the operation should be performed on the current database.
Enter fullscreen mode Exit fullscreen mode

->Create A Document:

->To create a document inside the collection 

->command:
        ->db.student.insertOne({name:'Athenian'})

        -> db.student.insertOne({name:'Ariadne',age:20,address:{palace:'knossos',country:'crete'},Personality:['Loving','Caring']})

->Note that here student is collections and we have created a document(row) inside it

->To add multiple rows use insertMany
    ->command:
        -> db.student.insertMany([{name:'Minos'},{name:'Minotaur'}])
        ->Note:to insert multiple rows you have to define arrays of document using []
Enter fullscreen mode Exit fullscreen mode

->Show Documents

->To read information from database

->Get all documents:
    ->command:db.student.find()

->If we want to see Database in more cleaner way we use pretty
    ->command:db.students.find().pretty()

->Find Document That matches it
    ->command:db.student.find({name:'Ariadne'})

->Find Document that matches object as well as return only the specified field
    ->command:db.student.find({name:'Ariadne'},{name:1,address:1})
    ->Note:The value 1 represents the inclusion of a field, while 0 can be used to exclude a field from the results. 

->  Find Document that matches the first document and returns the first document only
    ->command:db.student.findOne({age:20})

->Count Document that matches 
    ->db.student.countDocuments({age:{$gte:20}})
Enter fullscreen mode Exit fullscreen mode

->Read Modifers:

->limit:
    ->return the number of documents that are asked
    ->command:db.student.find().limit(2)

->sort:

    ->It  is used to sort the documents in a collection based on one or more fields.
      It allows you to specify the sorting order as either ascending (ascending order, indicated by 1) 
      or descending (descending order, indicated by -1) for each field.

    ->Sorting by Single Field in Ascending Order:

            ->command:db.student.find().sort({name:1})

    ->Sorting by Multiple Fields:

            ->This sorts the documents primarily by the age field in ascending order and,
            for documents with the same age, sorts them by the name field in descending order.

            ->command: db.student.find().sort({name:1,age:-1})

    ->Sorting in Descending Order:

            ->command:db.student.find().sort({name:-1})

    ->Sorting by Nesting Field:
            ->command:db.student.find().sort({'address.place':1})



    ->Note:if you don't specify any sorting criteria inside the sort() method in MongoDB, 
           the documents will be returned in their natural order, which is typically the order
           they were inserted into the collection.
            eg: db.student.find().sort()

->skip:
    ->skips the number specified from beginning
    ->command:db.student.find().skip(2)
Enter fullscreen mode Exit fullscreen mode

->Simple Filters:

    ->Check for Equality:
        ->$eq
        ->command: db.student.find({name:{$eq:'Ariadne'}})
        ->Check for all students with name 'Ariadne'

    ->Check for Not Equal:
        ->$ne
        ->command: db.student.find({name:{$eq:'Ariadne'}})
        ->Returns all the students which is not name as 'Ariadne'

    ->Check for Greater Than:
        ->$gt
        ->command:db.student.find({age:{$gt:40}})
        ->returns all the students whose age is greater than 40
        ->To check for greater than equally use $gte

    ->Check for Lesser Than:
        ->$lt
        ->command:db.student.find({age:{$lt:30}})
        ->returns all the students whose age is less than 30
        ->To check for lesser than equally use $lte

    ->Check one or many values is there 
        ->$in
        ->command:db.student.find({name:{$in:['Ariadne','Minos']}})
        ->returns all the student whose name is ariadne and minos

    ->Check none or many values is there :
        ->$nin
        ->command:db.student.find({name:{$nin:['Ariadne','Minos']}})
        ->returns all the student whose name is not ariadne and minos

    ->Check if Field Exist or Not:
        ->$exists
        ->command:db.student.find({age:{$exists:true}})
        ->Check if the field age exist and returns it

    ->To Check Multiple Conditions are true:
        ->$and
        ->command:db.student.find({$and:[{age:20},{name:'Ariadne'}]})
        ->Alternative:Comma Sepreated Value(will do and operation by default)
                        ->db.student.find({age:20,name:'Ariadne'})

    ->To check if one of the multiple condition is true:
        ->$or
        ->command:  db.student.find({$or:[{age:{$gt:10}},{name:'Minotaur'}]})

    ->Check all the values other than the value
        ->$not
        ->command:db.student.find({age:{$not:{$gt:30}}})

    ->Do comparision between different object
        ->$expr
        ->db.student.find({ $expr: { $gt: [“$rollno”, “$age”] } })
Enter fullscreen mode Exit fullscreen mode

->Update Document:

    ->updateOne:
        ->Only update the first document that matches the first object and update it with second object
        ->command:db.student.updateOne({age:20},{$set:{age:21}})
        ->update the age to 21 from 20
    ->updateMany:
        ->Update all the documents which matches the first object and update all with second object.
        ->command:db.student.updateMany({age:21},{$set:{age:22}})
        ->it will update all the document which has age 21 and update it to 22
Enter fullscreen mode Exit fullscreen mode

->Update Filters:

->$inc:
    ->Increments the value by the given value
    ->command:db.student.updateOne({age:22},{$inc:{age:3}})
    ->it increments the value by 3 and sets the age to 25 from 22
->$rename:
    ->rename the field
    ->command:db.student.updateMany({},{$rename:{age:"years"}})
    ->it will rename the field age to years
->$unset:
    ->to remove a field
    ->command:db.student.updateOne({years:60},{$unset:{years:""}})
->$push:
    ->Add a value to an array field
    -> command:db.student.updateOne({ years: 25 }, { $push:{mastery:'lasso'} } )
->$pull:
    ->Remove a value from array field
    ->command:db.student.updateOne({ years: 25 }, { $pull:{mastery:'lasso'} } )
Enter fullscreen mode Exit fullscreen mode

->Delete Document:

->To delete a single document:
    ->command:db.student.deleteOne({name:'Ariadne'})
->To delete multiple document`
    ->command:db.student.deleteMany({age:25})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)