Monday 7 December 2020

MongoDB Basics


Stores JSON objects in BSON format. 

Javascript based. Allows to query in javascript style.


Master-Slave architecture - shards and replicasets

There is a router with a table of contents and shard keys using which it decides where to query the data and in some cases multiple shards.

mongos - process which manages cluster

client connects to mongos


> use recipe

switched to db recipe

> show dbs

admin   0.000GB

config  0.000GB

local   0.000GB

recipe  0.000GB


db.<collectionName>.insertOne({<entire json document to be inserted>}) -> this will dynamically create a collection


db.<collectionName>.find({"fieldToQuery":"valueOfFieldToQuery"}, {"filedstLimitOutput": 1})

.sort("fieldToSortBy": 1).limit(1).skip(1)


> show collections

recipe


> db.recipe.find({}, {"title": 1});

{ "_id" : ObjectId("5f8c85634e5ccd1948fb7611"), "title" : "Zucchini Brownies" }

{ "_id" : ObjectId("5f8c88a94e5ccd1948fb7612"), "title" : "Chicken Soft Tacos" }

{ "_id" : ObjectId("5f8c88ee4e5ccd1948fb7613"), "title" : "Pancakes" }


> db.recipe.find({"title" : "Pancakes"}, {"title": 1});

{ "_id" : ObjectId("5f8c88ee4e5ccd1948fb7613"), "title" : "Pancakes" }


> db.recipe.find({},{"title": 1}).sort({"title":1});

{ "_id" : ObjectId("5f8c88a94e5ccd1948fb7612"), "title" : "Chicken Soft Tacos" }

{ "_id" : ObjectId("5f8c88ee4e5ccd1948fb7613"), "title" : "Pancakes" }

{ "_id" : ObjectId("5f8c85634e5ccd1948fb7611"), "title" : "Zucchini Brownies" }


> db.recipe.find({},{"title": 1}).sort({"title":1}).limit(1);

{ "_id" : ObjectId("5f8c88a94e5ccd1948fb7612"), "title" : "Chicken Soft Tacos" }


> db.recipe.find({},{"title": 1}).sort({"title":1}).limit(1).skip(1);

{ "_id" : ObjectId("5f8c88ee4e5ccd1948fb7613"), "title" : "Pancakes" }


# nested objects can also be queried

> db.recipe.find({"ingredients.name" : "egg"}, {"title" : 1});

{ "_id" : ObjectId("5f8c85634e5ccd1948fb7611"), "title" : "Zucchini Brownies" }

{ "_id" : ObjectId("5f8c88ee4e5ccd1948fb7613"), "title" : "Pancakes" }


# querying arrays

> db.recipe.find({"tags" : "easy"}, {"title" : 1});

{ "_id" : ObjectId("5f8c85634e5ccd1948fb7611"), "title" : "Zucchini Brownies" }

{ "_id" : ObjectId("5f8c88a94e5ccd1948fb7612"), "title" : "Chicken Soft Tacos" }


# match both entries in an array

> db.recipe.find({"tags" : {$all: ["easy","mexican"]}}, {"title" : 1});

{ "_id" : ObjectId("5f8c88a94e5ccd1948fb7612"), "title" : "Chicken Soft Tacos" }


# match either entries in an array

> db.recipe.find({"tags" : {$in: ["easy","mexican"]}}, {"title" : 1});

{ "_id" : ObjectId("5f8c85634e5ccd1948fb7611"), "title" : "Zucchini Brownies" }

{ "_id" : ObjectId("5f8c88a94e5ccd1948fb7612"), "title" : "Chicken Soft Tacos" }


#using expression

> db.recipe.find({$and :[{"ingredients.name" : "egg"}, {"ingredients.name" : "milk"}]}, {"title" : 1});

{ "_id" : ObjectId("5f8c88ee4e5ccd1948fb7613"), "title" : "Pancakes" }



$regex - for doing a regex search on a field


can store arrays, nested documents


comparison operators:

$eq, $lt, $lte, $gt, $gte, $ne, $in, $nin


logical operators:

$and, $or, $not


evalution:

$exists - to match documents with specified field


$where - documents satisfying javascript expression


it even have geospatial evaluation operators - $geoWithin, $geoIntersects etc


db.<collectionName>.updateOne({"fieldToQuery":"valueOfFieldToQuery"}, {$set :{"filedstLimitOutput": 1}});


> db.recipe.updateOne({"title" : "Zucchini Brownies" }, {$set: {"title" : "Zucchini Browniesss" }});

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }


$push $pull can be used for updating data in an array


# for getting the execution statistics, explain("executionStats") can be used

db.recipe.find({"tags" : {$in: ["easy","mexican"]}}, {"title" : 1}).explain("executionStats");


Reference documentation - https://docs.mongodb.com/manual/reference


sample_json = {

   "title":"Zucchini Brownies",

   "calories_per_serving":271,

   "comments": [{

      "body": "This is really gross.",

      "date": {

          "$date": "2020-09-07T18:42:30.000Z"

      },

      "name": "Caderyn Jenkins",

      "user_id": 1

  }, {

      "body": "Who thought of this? It's so bad.",

      "date": {

          "$date": "2000-02-03T18:42:30.000Z"

      },

      "name": "Grace Hopper",

      "user_id": 2

  }],

   "cook_time":32,

   "desc":"Don't worry, they won't turn out green",

   "directions":[

      "Combine brownie mix with other ingredients",

      "Bake as it says on box",

      "Don't actually make or eat this."

   ],

   "ingredients":[

      {

         "amount":{

            "quantity":1,

            "unit":"cup"

         },

         "name":"butter"

      },

      {

         "amount":{

            "quantity":2,

            "unit":null

         },

         "name":"egg"

      },

      {

         "amount":{

            "quantity":0.75,

            "unit":"cup"

         },

         "name":"plain yogurt"

      },

      {

         "amount":{

            "quantity":0.75,

            "unit":"cup"

         },

         "name":"shredded zucchini"

      },

      {

         "amount":{

            "quantity":0.75,

            "unit":"cup"

         },

         "name":"chocolate chips (semisweet)"

      },

      {

         "amount":{

            "quantity":3,

            "unit":"lbs"

         },

         "name":"creamy peanut butter"

      },

      {

         "amount":{

            "quantity":1,

            "unit":null

         },

         "name":"brownie mix"

      }

   ],

   "prep_time":12,

   "rating":[

      1,

      1,

      1,

      1,

      5

   ],

   "rating_avg":1.8,

   "servings":12,

   "tags":[

      "sweets",

      "easy"

   ],

   "type":"Dessert"

}


db.recipe.insertOne(sample_json);


Start/Stop mongod services in Mac:

brew services start mongodb-community@4.4

brew services stop mongodb-community@4.4



No comments:

Post a Comment