CRUD Operations in MongoDB

CRUD Operations-Creating Objects

Introduction

What are CRUD Operations

Basic Create, Read, Update, Delete Operations

Create or Insert (db.collection.insertOne()) Read or Find (db.collection.find()) Update (db.collection.updateOne()) Delete (db.collection.deleteOne())

Create Operation

Create Operation with Compass

open-exclusively
open-exclusively

Import Data from JSON or csv file. you can also add single record or document in table/collection with compass

open-exclusively
open-exclusively

Create Operation with Command Line

/* Connect to MongodB Atlast
Use your servername and username/password
*/
mongo "YourConnectionString"  --username newuser --password newpassword

/*Create Database by use command,
it will create database in memory but will not show in the cluster untill you create collection */
use sqlauthority

/* Show all databases in cluster */
show dbs

/* Show current working Db */
db

/* create collection in current db or in use db */
db.createCollection("newusers")

/* show collection */
show collections

/* insert single document
db is current in use selected db,
newuser is collection or table
insertone will insert or add a single record
 */
db.newusers.insertOne(
{
    "DisplayName": "Pinal Dave",
    "UserName": "pinaldave",
    "Job": {
        "Title": "DBA",
        "Area": "Database Performance Tuning",
        "isManager": "false"
    },
    "Programming Languages": ["T-SQL", "JavaScript", "HTML"]
}
)


/* Read from the collection
will output the JSON but not formated
*/
db.newusers.find( {} )
// .pretty() will format the JSON output
db.newusers.find( {} ).pretty()

/* insert multiple document, for this we create and array of objects and pass into insertMany operator as argument */
db.newusers.insertMany(
[
{
    "DisplayName": "Pinal Dave",
    "UserName": "pinaldave",
    "Job": {
        "Title": "DBA",
        "Area": "Database Performance Tuning",
        "isManager": "false"
    },
    "Programming Languages": ["T-SQL", "JavaScript", "HTML"]
},
{
    "DisplayName": "Jason Brown",
    "UserName": "jasonbrown",
    "Job": {
        "Title": "DBA",
        "Area": "Database Performance Tuning",
        "isManager": "true"
    },
    "Programming Languages": ["T-SQL", "JavaScript", "HTML"]
},
{
    "DisplayName": "Mark Smith",
    "UserName": "marksmith",
    "Job": {
        "Title": "DBA",
        "Area": "Database Development",
        "isManager": "false",
	"YearsExp":{"$numberInt":"5"}
    },
    "Programming Languages": ["T-SQL", "JavaScript"]
}
]
)

/* Read from the collection*/
db.newusers.find( {} )

db.newusers.find( {} ).pretty()

Insert single document into the collection db.collection.insertOne() Insert multiple documents into the collection db.collection.insertMany()

Things To Remember for Insert Behavior

  • Atomicity All write operation in MongoDB are atomic on the level of a single document.

    if the collection does not currently esist, insert operations will create the collection.

    if an inserted document omits the _id field, the MongoDB driver automatically generates and ObjectId for the _id field.

id fill must be unique in your collection.

  • Collection Creation
  • _Id

CRUD Operations- Retrieving Objects

Things To Remember for Find Behavior

query and projection are important if using mongodb locally db.collection.find() accepts following three parameters. db.collection.find()

  • Query
  • Projection
  • Read Concern // needed for clustes

Query and Query Operators

https://docs.mongodb.com/manual/reference/operator/query/

Find method support manay different query operators to filter data

  • Comparison
  • Logical
  • Element
  • Evaluation
  • Geospatial
  • Array
  • Bitwise

Query Projection

Specifies the fields to return in the documents that match the query filter

  • 1 or true : include the field
  • 0 or false : exclude the field

Read Concern

Allows to control the consistency and isolation properties of the data readfrom replica sets and replica set shards

  • Local
  • Available Most of the cases majority read concerns is good enough.
  • Majority
  • Linearizable
  • Snapshot

CRUD Operations- Retrieving Objects with Compass

{} // retrive all the records

// retrive all the records in which runtime is equal to 11.
{runtime: 11}

/*
// retrive all the records in which runtime is equal to 11.
*/
{ runtime: {$eq: 11}}

// retrive all the records in which runtime is greater than 11.
{ runtime: {$gt: 11}}

// retrive all the records in which runtime is less than to 11.
{ runtime: {$lt: 11}}

// retrive all the records in which runtime is less than and equal to 11.
{ runtime: {$lte: 11}}


// querying an array:: retrive all the records in which Billy Bletcher is cast from array of values.
{ cast: "Billy Bletcher"}

// querying an Object:: retrive all the records in which awards.wins = 3, this awards is  object name and wins are the property of an object.
{"awards.wins":3}


// use of and operator
{$and: [{ runtime: {$gt: 80}}, {"awards.wins":3}]}

// use of or operator
{$or: [{"awards.wins":3},{ runtime: {$gt: 80}}]}
// click on options type following filter in project section
{title:1,runtime:1, "awards.wins":1, _id:0}

// click on options type following filter in sorting section, 1 means sort in asscending order, -1 means sort in descending order
{title:1}

CRUD Operations- Retrieving Objects using Command Line

/*Connect to MongodB Atlast
Use your servername and username/password
*/
mongo "YourConnectionString"  --username newuser --password newpassword

/*Create Database*/
use sample_mflix

/* Read from the collection*/
db.movies.find( {} )

db.movies.find( {} ).pretty()

db.movies.find( {runtime: 11} ).pretty()

db.movies.find( {runtime: 11} ).pretty().limit(3)

db.movies.find( {runtime: 11}, {title:1} ).pretty().limit(3)

db.movies.find( {runtime: 11}, {runtime:1, title:1, _id:0} ).pretty().limit(3)

db.movies.find( {runtime: {$eq: 11}}, {runtime:1, title:1, _id:0} ).pretty().limit(5).sort({title: 1})

db.movies.find( {runtime: {$eq: 11}}, {runtime:1, title:1, _id:0} ).pretty().limit(5).sort({title: -1})

db.movies.find( {runtime: {$eq: 11}}, {runtime:1, title:1, _id:0} ).pretty().limit(5).sort({title: -1}).readConcern("majority")

db.movies.find( {runtime: {$eq: 11}}, {runtime:1, title:1, _id:0} ).pretty().limit(5).sort({title: -1}).readConcern("linearizable").maxTimeMS(10000)


db.movies.find( {runtime: {$gt: 1}}, {runtime:1, title:1, _id:0} ).pretty().limit(300).readConcern("linearizable").maxTimeMS(10000)

CRUD Operations: Updating and Deleting Objects

Write Concern

Level of acknowledgement requested from MongoDB for write operations w:1 – Ack from primary w:0 – No ack w:(n) – Primary + (n-1) secondary w: majority wtimeout : Time limit to prevent write operations from blocking indefinitely

Update Operation

db.collection.updateOne() db.collection.updateMany() db.collection.replaceOne()

Things to Remember for Update Behavior

Atomic on the level of a single document _id field cannot be replaced with different Value $set creates field if not already existing upsert : true

  • Update on match of filter
  • Insert no match of filter

Updating Documents with command line

/* Connect to MongodB Atlast
Use your servername and username/password
*/
mongo "YourConnectionString"  --username newuser --password newpassword

use sample_mflix
// for finding current context
db

// simple update command to update one field
db.movies.updateOne(
{
    // this is text string we will want to update
    {title: {$eq: "The Old Crocodile"}},
    // this statement will replace the above title with new title
    {
        $set: {"title": "The New Crocodile" }
    }
}
)

// simple update command to update more than one field
db.movies.updateOne(
    {
        // this is text string we will want to update
        {title: {$eq: "The New Crocodile"}},
        // this statement will replace the above title with new title, if any of the field does not exist it will be created with defined value
        {
            $set: {"title": "The Old Crocodile", "year": 2020 }
        }
    }
)

//find command
db.movies.find( {year: {$eq: 1988}}).count()
// updateMany command
db.movies.updateMany(
    { year: {$eq: 1988}},
    {
        $set: {"year": 2025}
    }
)

// this query will update thre record, if it did not find the document that it was looking for to update it will insert that record, below query will insert `year: 1988` and then set command will update the year 1988 to year 2025
db.movies.updateMany(
{ year: {$eq: 1988}},
{
    $set: {"year": 2025}
},
{upsert: true}
)
// query with write concerns
db.movies.updateMany(
{ year: {$eq: 1988}},
{
    $set: {"year": 2025}
},
{upsert: true, w:"majority", wtimeout:1000 }
)

db.movies.replaceOne(
{runtime: {$eq: 1122 }},
{
    runtime: 1122, "NoTitle": "ReplaceOneExample"
}
)

Delete Operation

db.collection.deleteOne() db.collection.deleteMany() db.collection.remove()

Things to Remember for Delete Behavior

All write operations in MongoDB are atomic on the level of a single document. Delete does not drop indexes.

Next