{"id":16211993,"url":"https://github.com/tidbitsjs/basic-mongodb","last_synced_at":"2026-05-09T00:05:39.570Z","repository":{"id":110917467,"uuid":"317006063","full_name":"TidbitsJS/Basic-MongoDB","owner":"TidbitsJS","description":"Introduction to MongoDB","archived":false,"fork":false,"pushed_at":"2020-12-16T16:21:15.000Z","size":57,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-13T23:15:59.540Z","etag":null,"topics":["javascript","mongodb","node","nosql-database"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TidbitsJS.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-11-29T17:32:53.000Z","updated_at":"2024-08-20T03:43:59.000Z","dependencies_parsed_at":"2023-03-13T13:46:57.231Z","dependency_job_id":null,"html_url":"https://github.com/TidbitsJS/Basic-MongoDB","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TidbitsJS%2FBasic-MongoDB","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TidbitsJS%2FBasic-MongoDB/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TidbitsJS%2FBasic-MongoDB/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TidbitsJS%2FBasic-MongoDB/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TidbitsJS","download_url":"https://codeload.github.com/TidbitsJS/Basic-MongoDB/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247736709,"owners_count":20987681,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","mongodb","node","nosql-database"],"created_at":"2024-10-10T10:49:49.587Z","updated_at":"2026-05-09T00:05:34.550Z","avatar_url":"https://github.com/TidbitsJS.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Introduction to MongoDB\n\nWelcome to the README, where you will get to know about the basics of the very well known \"M\" in MERN or MEAN, i.e., the MongoDB\n\n#### Prerequisite - Repo contains source code from the \"The Complete Node.js Course\" by the \"Code With Mosh\" author.\n\nIt will be great if you follow the course, but no worries, I have got you covered here with the knowledge that I learned from the author. Stick with README, which won't be length nor cryptic. I hope - we - both grasp something insightful from this. Let's jump in!\n\n### WTH is MongoDB?\n\nAhh, there is this thing about tech - it never ceases to amaze you, isn't it? How we evolved from SQL database to NoSQL or Not SQL or Not SQL Database is something\nto note for. Don't worry, I am not taking you back in time. My Point is to familiarize you with these two points here: SQL \u0026 NoSQL. \n\n#### Meet `SQL` -  \n A mechanism to operate or manipulate data that we store in our hardware kinds of stuff. SQL aka relational database means the database that stores data in tabular form.\n\n#### Meet `NoSQL` - \n A mechanism that deals with data in an anti SQL way. NoSQL, meaning, literally nothing sort of tabular relations. \n It stores data in other formats including, a highly used [ Key - Value ] pair system ( JSON ), but it's not the only way it handles data. \n It also uses other data structures such as `Wide-Column Store`, `Graph database` or be that `Document-Oriented Database`. \n \nNow you have that slightest idea of SQL \u0026 NoSQL, let's deep dive to know further linking of NoSQL \u0026 MongoDB.\n\n`MongoDB` - NoSQL database programs which uses JSON-like documents with optional schemas. \n Meaning that you can create records without first defining the structure, such as the fields or the types of their values.\n \nThat will be a short description on what is MongoDB. You can always dig deeper. But for now, we will keep that deep theory aside and will jump on programming part.\n \nYou can refer the mentioned doc on \"How to setup mongoDB in your system\". [Install MongoDB](https://docs.mongodb.com/manual/installation/).\nAfter successful installation, you will have MongoShell \u0026 Mongod. By default, MongoDB starts at port 27017. \nWe need this to connect Mongoose to our MongoDB service so that we can use database in our application.\n\n`Mongoose` is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. More clearly, it's a JavaScript framework that is commonly used in a Node.js application with a MongoDB database.\n\n#\n\nAssuming that you have all your required setup running on your machine, let's work on code.\n\n```javascript\nconst mongoose = require('mongoose')\n\nmongoose.connect(\"mongodb://172.17.0.2:27017/playground\", \n  { useNewUrlParser: true, useUnifiedTopology: true })\n    .then(() =\u003e console.log('successfully connected to mongodb'))\n.catch((err) =\u003e { throw new Error(\"Oops an error\", err) })\n```\nNot to afraid, it's just a few lines of code on connecting your mongoose to mongoDB driver. How? Let me explain\n\n1. First, you import `mongoose` \n2. `mongoose.connect()` is a function which takes few parameters, which are, \n \na) The `url` - \"mongmongodb://172.17.0.2:27017/playground\", which is nothing but \"mongodb://localhost_address/db_name\". That `mongodb://` is a starting point and you should not miss. Remeber that! \n \nb) Object `{ useNewUrlParser: true, useUnifiedTopology: true }` - These are parameters you need to pass to take down the `deprecation warnings` thrown by the compiler. You might get those warnings or might not, depending upon the `mongoose` \u0026 `MongoDB` version you are using.\n\nWhile executing `mongoose.connect()` it will either throw an error or a successful connection message. To know what really happened in the hood, we use `.then()` \u0026 `.catch()` to display respective message.\n\n#### Note - The url `mongodb://localhost_address/db_name`  where you have to specify db_name, not necessarily need to exist before. If that db_name is already there, then MongoDB will use that db else it will create a new db of that name. Making our lives simpler.\n\nConsidering that you have successfully connected to MongoDB driver with the help of mongoose. Let's learn how to create a schema for our database.\n\nBefore diving into schema creation, I will like to mention a few of the necessary terminology for MongoDB\n\n1. Database - Same idea as of any SQL database. What differs is, SQL has tables \u0026 rows in their database, whereas MongoDB has collections.\n2. Collection - It is equivalent to a table in an SQL database.\n3. Document - SQL table has rows \u0026 columns. You guessed that right, MongoDB too has it's equivalent, named document. A document can be referred to as a SQL database row.\n4. Field - A field in a document, is like a column in a row of data in SQL. \n\nSo this is how the tree structure of MongoDB is - You have a Database, that database contains different collections where the collection is made up of a document \u0026 field.\n\n#\n\n#### What is Schema then?\n\nA document schema is a JSON object that allows you to define the shape and content of documents and embedded documents in a collection. - MongoDB Guide\n\nMeaning that, you are defining data structure or shape of a document i.e., what that document contains, a number, a string, or something else!\n\n```javascript\n\nconst playSchema = new mongoose.Schema({\n    nickname: String,\n    hobby: String,\n    job: String,\n    date: { type: Date, default: Date.now },\n    age: Number,\n    bookie: Boolean,\n    play: String,\n    tags: [String]\n})\n\n```\n\nBack to the code, here I am defining a schema named `playSchema` with the help of mongoose.Schema(). The object that has been passed to mongoose function is our schema structure. It defines a property in our documents which will be cast to its associated SchemaType.. Ex., nickname casts a String SchemaType, date to data SchemaType ( it's not object, date is one of schemaType ) or be that tags which casts an Array SchemType. These are some examples of built-in Mongoose Schema Types.\n\n`Note` - Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.\n\nMoving on to the next part, you see a code statement. What's that? \n\n```javascript\n\nconst Play = mongoose.model('Play', playSchema)\n\n```\nA variable named `Play` is assigned to a function of mongoose where I am passing two params, namely, `Play` (again) and `playSchema`. \n\nplaySchema is notable here, one can find out that we are passing our defined Schema to this `mongoose.model()`. Perfect. Let's learn what it actually does.\n\n#\n\n#### mongoose.model()\n\n`mongoose.model() is a wrapper on the mongoose schema. What did that mean? - A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.\n\nSomething similar to `Class`, you define the structure and then take an instance of that to manipulate data through the `new` keyword. The instance of Class. The interface of Schema. Got it? \n\nLet's crack the first and foremost parameter `Play`. It's the singular name of your collection that you are going to create in your database. Singular?  \n\nMongoose automatically looks for the plural, lowercased version of your model name. Thus, for the example above, the model `play` is for the `plays` collection in the database - mongoose Docs\n\n\u003e Note: The .model() function makes a copy of schema\n\nWe are yet to create a document in our collection called `Play` ( In the database it is `plays` ) in a database named `playground`. Losing interest?. Don't. Hang in there, the very next step is about creating the very first document in the database. Are you ready? \n\n#\n\nThe next piece of code is something like this -\n\n```javascript\nasync function playground() {\n    const play = new Play ({\n        nickname: 'Riley',\n        hobby: 'Playing',\n        job: 'Studying',\n        age: 11,\n        bookie: false,\n        play: 'Inside Out',\n        tags: ['Joy', 'Sadness', 'Anger', 'Fear', 'Disgust']\n    })\n    \n    const result = await play.save()\n    console.log('====================================');\n    console.log(result)\n    console.log('====================================');\n}\n```\n\nAn async function with few code statements executing in it. So far we have created our model and now we are trying to take the instance of this model. An instance of a model is called a document. Creating them and saving them to the database is easy. You get that right, use the `new` keyword to take the instance. That's what the first code block is trying to explain to you so far. \n\n```javascript\nconst play = new Play ({\n        nickname: 'Riley',\n        hobby: 'Playing',\n        job: 'Studying',\n        age: 11,\n        bookie: false,\n        play: 'Inside Out',\n        tags: ['Joy', 'Sadness', 'Anger', 'Fear', 'Disgust']\n })\n```\n\nVariable `play` is a document here that contains all those fields we have defined and compiled so far. Defining the Schema \u0026 creating a fancy constructor called `model`. So the first document has info about Riley whose hobby is playing, age is 11 with some other tags. Note that we haven't defined the `Date` field here. No value was provided. Go back, \u0026 take a look at the Schema definition. Yes, it says that, if you provide your document with any specific date, it will assign a date variable with it and if not, then it will, itself, write the current time to the field. So far So good, a document has been created. Let's save this using mongoose's built-in function. We have that luxury!\n\n```javascript\nconst result = await play.save()\n```\n\nKindly note it down, we have declared `playground()` as an asynchronous function. Meaning that there is something in function, which deals with promises, which returns a promise after its execution, be that reject or resolve, whatever it may be. To make this async code simpler, we have used `async/await`, which is the sugar coat of `Promises`. \n\nWith the schema and model set up, the mongoose save() method can now be used to insert a document into the “play” collection. The `play.save()` will either send an error or insert the document into our collection. You just need to simply console.log.\n\nNot to forget, you better call the `playground()` function to see the end result. And after that, you can check the inserted document \u0026 its collection in your mongo shell by executing a few commands.\n\n# \n\nWhile you might have successfully inserted a document in the database, this is not what we wanted. Why do I say so? See, you did everything right up to this point, no doubt. But what remains is accessing those documents from the database of a specific collection. Cause that's what we need, save data \u0026 display it later to a user.\n\nAfter running the `playground()` function, you might see an object ended up in your console. The `result` variable. It outputs how our document has been inserted into the database by MongoDB. Yes, the `id field`. It is a unique number given to every document by MongoDB. Well, you can give an id of your choice anytime. But you will have to make sure it's novel and is given to every document out there. The choice is always yours.\n\nBack to the point, `result` is displaying what we have entered just now. We don't know the past data record at all. No idea. This is where,` Queries` come to help us to backtrack the data back into our application. Yeah, that's what we want. Without further due, let's jump right on Query Track.\n\n#### Query of Query\n\nThere are various ways to query a document from the MongoDB database. It can be a normal Query, Logical Query, Comparison Query, or Regular Expression Query. Anything.\n\nHere is a simple hands-on fo simple normal Query - \n\n```javascript\nasync function getPlays() {\n\n    const plays = await Play\n            .find({ bookie: false }) \n\n    console.log('====================================');\n    console.log(plays);\n    console.log('====================================');\n}\n```\nTry not to get thrown by the naming conventions that I have used. Rather try to read the code properly for a minute. As we are dealing with asynchronous code, you can clearly see async/await.\n```javascript\nconst plays = await play.find({ bookie: false })\n```\n\nThe code statement is to get those documents that have the `bookie: false` field in them. The `Play.find({ key: value })` is a simple query where you can retrieve any amount of document by passing a certain parameter. It's not mandatory to though. If you just thought of calling `Play.find()`, no problem, you are not going to deal with unknown errors. It's a valid code. Calling that statement will lead to the complete display of all the documents that are present in the database. You will get an array of objects as an output on your console.\n\n#\n\nMoving ahead in the course, Author Mosh teaches us some different types of queries including comparison query ( less than, greater than, equal to and so forth remaining ), logical query ( OR \u0026 And ), and a few queries based on the regular expressions. Let's know them in detail.\n\n```javascript\nconst plays = await Play \n    .find({ age: { $gte: 10, $lte: 20 } })\n```\n\nDecoding the above code will lead us to a result of documents that have their age field either greater than equal to 10 ( `$gte: 10` )  or less than equal to 20 ( `$lte: 10` ). Simple as it is. Let's do one more such query.\n\n\n```javascript\nconst plays = await Play \n    .find({ age: { $in: [5, 10, 15] } }) \n```\n\nWhen used above code as a query on your documents, it will output those specific documents whose age field is similar to specified elements in the array `$in: [5, 10, 15]`. Telling us that, the resulted documents will have ages as 5, 10, or 15.  \n\nBelow is the list of Comparison Query Operators - \n\n1) `$eq` - Matches values that are equal to a specified value.\n2) `$gt` - Matches values that are greater than a specified value.\n3) `$gte` - Matches values that are greater than or equal to a specified value.\n4) `$in` - Matches any of the values specified in an array.\n5) `$lt` - Matches values that are less than a specified value.\n6) `$lte` - Matches values that are less than or equal to a specified value.\n7) `$ne` - Matches all values that are not equal to a specified value.\n8) `$nin` - Matches none of the values specified in an array.\n\nGo grab a cookie or have a cup of coffee and start playing with data using those operators. I bet, it will be great fun.\n\n# \n\nTime to move on ( to next Query ). The second most coming to the list is, Logical Query. Here is the sample code on how to use a logical query on your documents.\n\n```javascript\nconst plays = await Play\n      .find()\n      .or([{ age: { $gte: 5, $lte: 20  } }, { bookie: false }])\n```\n\nClearly, it's stating that, return every document (`.find()` - No filters here ) where the document field has `Age` either `Greater than equal to 5 or Less than equal to 20` OR `bookie is false`. Note that capitalized \"OR\". This is what our logical query operator is. You can use \"AND\" as well. Like this -\n\n\n```javascript\nconst plays = await Play\n      .find()\n      .and([{ age: { $gte: 5, $lte: 20  } }, { bookie: false }])\n```\n\nWe can play a little more here. Adding a few more methods on our modal to get more filtered documents. For example, limiting the number of documents, or sorting that in a particular order. Interesting right?\n\n```javascript\nconst plays = await Play\n      .find()\n      .or([{ age: { $gte: 5, $lte: 20  } }, { bookie: false }])\n      .limit(10)\n      .sort({nickname: 1})\n```\n\nContinuing the above \"OR\" equation with new modifications, the output will be an array of documents limited to 10 and sorted by nickname in ascending order.\n\n`.limit(x)` - Limits the number of documents passed to the next stage. x can be any positive number\n`.sort(1)` - Sort ascending.\n`.sort(-1)` - Sort descending.\n\n\nWell, this is not the end of Logical Query. You can use logical operations in another way too. I have had found this recently on MongoDB docs. Why not mention them here too?\n\nList of Logical Query Operators -\n\n1) `$and` - Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.\n2) `$not` - Inverts the effect of a query expression and returns documents that do not match the query expression.\n3) `$nor` - Joins query clauses with a logical NOR returns all documents that fail to match both clauses.\n4) `$or` - Joins query clauses with a logical OR returns all documents that match the conditions of either clause.\n\nBesides listing these out, let's try the above `.or()` problem into the new `$or`.\n\n```javascript\nconst plays = await Play\n     .find({ $or: [ { age: { $gte: 5, $lte: 20 } }, { bookie: false } ] })\n```\nThe result is going to be the same. These are just different ways of doing the same thing. You can choose any.\n\n#\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftidbitsjs%2Fbasic-mongodb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftidbitsjs%2Fbasic-mongodb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftidbitsjs%2Fbasic-mongodb/lists"}