{"id":19606759,"url":"https://github.com/learnwithfair/mongodb-documentation","last_synced_at":"2026-05-12T21:12:01.010Z","repository":{"id":237536355,"uuid":"794670287","full_name":"learnwithfair/mongodb-documentation","owner":"learnwithfair","description":"MongoDB documentation with [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]","archived":false,"fork":false,"pushed_at":"2024-05-01T18:03:15.000Z","size":189,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-26T16:50:01.700Z","etag":null,"topics":["database","documentation","learn-with-fair","learnwithfair","mern","mern-stack","mongodb","mongodb-atlas","nosql","rahatul-rabbi","rahatulrabbi","webdevelopment"],"latest_commit_sha":null,"homepage":"","language":null,"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/learnwithfair.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":"2024-05-01T17:50:02.000Z","updated_at":"2024-05-01T18:03:18.000Z","dependencies_parsed_at":"2024-05-02T12:22:45.360Z","dependency_job_id":"f71a9ba4-f68b-49b6-9934-8db0786d8465","html_url":"https://github.com/learnwithfair/mongodb-documentation","commit_stats":null,"previous_names":["learnwithfair/mongodb-documentation"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/learnwithfair/mongodb-documentation","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmongodb-documentation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmongodb-documentation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmongodb-documentation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmongodb-documentation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learnwithfair","download_url":"https://codeload.github.com/learnwithfair/mongodb-documentation/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fmongodb-documentation/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32957157,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-12T09:19:52.626Z","status":"ssl_error","status_checked_at":"2026-05-12T09:17:33.438Z","response_time":102,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["database","documentation","learn-with-fair","learnwithfair","mern","mern-stack","mongodb","mongodb-atlas","nosql","rahatul-rabbi","rahatulrabbi","webdevelopment"],"created_at":"2024-11-11T10:07:07.302Z","updated_at":"2026-05-12T21:12:00.980Z","avatar_url":"https://github.com/learnwithfair.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# MONGODB-DOCUMENTATION\n\nThanks for visiting my GitHub account!\n\n\u003cimg src =\"https://www.svgrepo.com/show/331488/mongodb.svg\" height = \"200px\" width = \"200px\"/\u003e **MongoDB** is a document database. It stores data in a type of JSON format called BSON. Also, **MongoDB** is a source-available, cross-platform, document-oriented database program. Classified as a NoSQL database product, MongoDB utilizes JSON-like documents with optional schemas. [see-more](https://www.w3schools.com/mongodb/)\n\n## CODE EXAMPLE\n\n- [Code-Example1](https://github.com/learnwithfair/mern-ecommerce-with-postman)\n- [Code-Example2](https://github.com/learnwithfair/node-express-documentation)\n\n## Source Code (Download)\n\n[Click Here](https://mega.nz/folder/RGFiUApD#PoKIVCwF8IkQhE2PHw1XxQ)\n\n## Required Software (Download)\n\n- VS Code, Download -\u003ehttps://code.visualstudio.com/download\n- Node, Download-\u003e https://nodejs.org/en/download\n- MongoDB Shell(msi) , Download-\u003e https://www.mongodb.com/try/download/shell\n- MongoDB Compass (msi), Download-\u003e https://www.mongodb.com/try/download/community\n- Postman, Download-\u003e https://www.postman.com/downloads/\n\n**Or Online Database (MongoDB Atlas)**\n\n- Register -\u003e https://www.mongodb.com/cloud/atlas/register\n\n## ========== Environment Setup ==========\n\n1. Install Node.js\n2. To verify installation into command form by node -v\n3. For initialization npm write the query in the command window as npm init -y\n4. Setup the opening file into the package.json and change the file with main:'server.js'\n5. To create a server using the express package then write a query into the command window as npm install express.\n   Write code in the server file for initialization\n   const express = require(\"express\");\n   const app = express();\n   app.listen(3000, () =\u003e {\n   console.log(\"Server is running at http://localhost:3000\");\n   });\n\n6. Install the nodemon package for automatically running the server as- npm i --save-dev nodemon (For Developing purpose)\n7. setup the package.json file in the scripts key, write\n   \"scripts\": {\n   \"start\": \"node ./resources/backend/server.js\",\n   \"dev\": \"nodemon ./resources/backend/server.js\",\n   \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\"\n   },\n8. use the Morgan package for automatic restart. Hence install the morgan package as npm install --save-dev morgan (Development purpose)\n   Write code in the server file for initialization\n   const morgan = require(\"morgan\");\n   app.use(morgan(\"dev\")); --\u003e Middlewire.\n9. Install Postman software for API testing by the URL endpoint.\n10. Install Mongobd + MongobdCompass and Mongoshell (For Database)\n\n## ========== Connect MongoDB Database ==========\n\n1. Install Mondodb + Mongodb Compass and Mongodb Shell download from the google.\n2. Set up Environment Variable in drive:c/program file\n3. Create a directory in the base path of the c drive named data. Inside the data directory create another folder db.\n4. Write the command in the CMD window as Mongod. And write the other command in the other CMD window as mongosh.\n5. Then Check the version as mongod --version and mongosh --version.\n6. Install mongoose package as npm i mongoose\n7. Create an atlas account. In the atlas account create a cluster that have a user(as atlas admin) and network access with any access IP address.\n8. Connect the database using URL from the atlas cluster or local Mongodb compass using the mongoose package as mongoose. connect('mongodb://localhost:27017/database-name);\n\n## Project Schema\n\n|                              |\n| :--------------------------: |\n|            Schema            |\n| ![schema](images/schema.jpg) |\n\n## 0. SQL VS NoSQL\n\n- SQL stands for Structured Query Language - MySQL Database\n  - It follows relational database management system\n  - store data as a form of table\n  - null possibility if we dont add value for column\n- NoSQL stands for No Structured Query Language - MongoDB Database\n  - It follows documented oriented database management system\n  - store data as a form of document by using BSON structure\n  - no null possibility if we do not add add value for any field\n  - it uses BSON -\u003e Binary JSON\n- why BSON instead of JSON?\n  - JSON only supports limited number of data types such as String, Boolean, Number, Array (BSON added Date, Raw Binary, Number-Integer, Float, Long, Decimal to JSON)\n  - Speed - text based format is very slow to parse (BSON is fast to parse)\n  - Storage - JSON takes less compare to BSON\n  - Usage - JSON used for transmission data where BSON used for storage of data\n  - Encoding technique: JSON use UTF-8 string encoding where BSON use Binary encoding\n  - Security: JSON is Human and machine Readable where BSON in only machine Readable\n\n## 1. Introduction to MongoDB\n\n- What is MongoDB?\n\n  - Document Oriented Database system\n  - NoSQL\n  - Some important terms: Database, Table/Collection, Document/Row, Field/Column\n\n  ```js\n    // document example\n      {\n        id : '1',\n        name: 'rahatul',\n        languages: ['bangla', 'english']\n\n      }\n  ```\n\n## 2. Environment setup\n\n- Download \u0026 install MongoDB\n- MongoDB Compass\n- Check installation\n\n  ```js\n  mongod --version (mongodb server version)\n  mongo --version (mongodb shell version)\n  ```\n\n## 3. Basic command\n\n- database\n\n  - show databases: `show dbs`\n  - create / switch to a Database: `use databaseName` example: `use productsDB`\n  - check the Database you are in : `db + enter`\n  - drop database : `db.dropDatabase()`\n\n- collections\n  - show collections: `show collections`\n  - create collection : `db.createCollection(name, option)`\n    example `db.createCollection(\"products\")`\n  - drop collection : `db.collectionName.drop()`\n\n## 4. CRUD - Create Document\n\n- database is collection of Documents\n- Field name regulations collected from MongoDB official website:\n  - The field name \\_id is reserved\n  - Field names cannot contain the null character.\n- insert documents command\n  - `db.collectionName.instertOne({})`\n  - `db.collectionName.instertMany([{},{}])`\n  - `db.collectionName.instert([{},{}])`\n- Create data- inserting data to user collection example\n\n  ```js\n    {\n      title: \"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops\",\n      price: 109.95,\n     }\n\n  // insertOne()\n   db.products.insertOne({\n      title: \"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops\",\n      price: 109.95,\n     })\n\n  // insertMany()\n   db.products.insertMany([\n    {\n      title: \"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops\",\n      price: 109.95,\n     },\n     {\n      title: \"Mens Casual Premium Slim Fit T-Shirts \",\n      price: 22.3,\n     },\n     {\n      title: \"Mens Cotton Jacket\",\n      price: 55.99,\n     }\n     ])\n\n  ```\n\n## 5. CRUD - Read Document\n\n- Read / Find data\n\n  - read data syntax: `db.collectionName.find(query, projection)`\n  - read data in an easy way syntax: `db.collectionName.find().pretty()`\n  - read a specific data syntax: `db.collectionName.find({field: fieldValue})`\n    - example1: `db.products.find(ObjectId(\"633d183e09743587af26fb07\"))`\n    - example2: `db.users.find({name: \"anisul islam\"})` remember value is case sentitive\n  - limit data syntax: `db.collectionName.find({field: fieldValue}).limit(NumberOfRows)`\n    - example: `db.users.find({age: 31}).limit(2)`\n  - sorting: 1 for ascending, -1 for descending\n    - example: `db.products.find().sort({price: -1})`\n  - [less than and greater than](https://www.statology.org/mongodb-greater-than-less-than/#:~:text=You%20can%20use%20the%20following,%24gt%3A%20Greater%20than)\n    - example : `db.myCollection.find({field1: {$gt:25}})`\n  - projection\n    - example : `db.students.find({name: \"x\"}, {name:0})` get every field without name\n    - example : `db.students.find({name: \"x\"}, {name:1})` get only field\n    - example : `db.students.find({name: \"x\"}, {_id:0, name:1})` get only field even without mongodb \\_id\n\n## 6. CRUD - Update Document\n\n- Update Data -\u003e $set operator helps to set update value to a field\n\n  - update data syntax: `db.collectionName.update(selection_item, update_data)`\n  - update data syntax: `db.collectionName.updateOne(selection_item, update_data)`\n  - update data syntax: `db.collectionName.updateMany(selection_item, update_data)`\n  - find one and update data syntax: `db.collectionName.findOneAndUpdate(selection_item, update_data)`\n  - example: `db.products.update({id:\"1\"},{$set:{price:32}})`\n\n## 7. CRUD - Delete Document\n\n- Delete data\n\n  - delete data syntax: `db.collectionName.deleteOne(selection)\n    - example: `db.users.deleteOne({name:\"anisul islam\"})`\n  - delete data syntax: `db.collectionName.deleteOne()\n  - delete many data syntax: `db.collectionName.deleteMany({selected_item})\n  - delete many data syntax: `db.collectionName.deleteMany({})\n\n## 8. CRUD Operations in MongoDB Compass\n\n## 9. Node.js and mongodb connection\n\n- 2 ways to connect -\u003e with mongoose package, with mongodb package\n- method 1: with mongodb package\n  - install mongodb : `npm i mongodb`\n- method 2: with mongoose package\n  - mongoose in an ODM (Object data modeling) Library for MongoDB and node.js. It provides schema validation. node.js -\u003e mongoose -\u003e mongo driver -\u003e mongoDB\n\n```js\nconst express = require(\"express\");\nconst mongoose = require(\"mongoose\");\n\nconst port = 3002;\nconst app = express();\n\nconst connectDB = async () =\u003e {\n  try {\n    await mongoose.connect(\"mongodb://localhost:27017/shop\");\n    console.log(\"db is connected\");\n  } catch (error) {\n    console.log(error);\n  }\n};\n\napp.listen(port, async () =\u003e {\n  console.log(`server is running at http://localhost:${port}`);\n  await connectDB();\n});\n```\n\n## 10. Mongoose schema \u0026 model\n\n- define structure of document with validation\n- we can define default values of a field\n- A model works as a wrapper for schema. It provides an interface for accessign database to create, update, delete, read from database.\n\n```js\nconst productSchema = new mongoose.Schema({\n  title: {\n    type: String,\n    reuired: true,\n  },\n  description: {\n    type: String,\n    reuired: true,\n  },\n  price: {\n    type: Number,\n    reuired: true,\n  },\n  date: {\n    type: Date,\n    default: Date.now,\n  },\n});\n\nconst Product = mongoose.model(\"Products\", productSchema);\n```\n\n## 11. Create document from node.js\n\n```js\nconst addProduct = async () =\u003e {\n  try {\n    const newProduct = new Product({\n      title: \"iPhone 14\",\n      description: \"a nice cute product\",\n      price: 1300,\n    });\n    const productData = await newProduct.save();\n    // insert many\n    // const productData = await Product.insertMany([newProduct1, newProduct2]);\n    console.log(productData);\n  } catch (error) {\n    console.log(error.message);\n  }\n};\naddProduct();\n```\n\n## 12. Read document from Database in node.js \u0026 comparsion query operators\n\n- comparsion query operators: https://www.mongodb.com/docs/manual/reference/operator/query-comparison/\n  - $eq, $ne, $gt, $lt, $gte, $lte, $in, $nin\n\n```js\nconst getProducts = async (req, res) =\u003e {\n  try {\n    const products = await Product.find();\n    const products = await Product.find().limit(1);\n    const products = await Product.find({ id: req.params.id });\n    const products = await Product.find({ isAvailable: true });\n    const products = await Product.find({ price: { $eq: 1200 } });\n    const products = await Product.find({ price: { $in: [1200, 1300] } });\n    const products = await Product.find({ price: { $nin: [1200, 1300] } });\n    const products = await Product.find({ price: { $ne: 1200 } });\n    const products = await Product.find({ price: { $gt: 1200 } });\n    const products = await Product.find({ price: { $lt: 1200 } });\n    const products = await Product.find({ price: { $gte: 1200 } });\n    const products = await Product.find({ price: { $lte: 1200 } });\n    const products = await Product.find({ price: 1200 });\n\n    const products = await Product.find({ price: { $gt: 1200 } }).select({\n      title: 1,\n    });\n    const products = await Product.find({ price: { $gt: 1200 } }).select({\n      _id: 0,\n      title: 1,\n    });\n\n    const products = await Product.find({ price: { $gt: 1200 } }).select({\n      _id: 0,\n      title: 0,\n    });\n\n    console.log(products);\n  } catch (error) {\n    console.log(error);\n  }\n};\ngetProducts();\n```\n\n## 13. Query Operators: Logical operators\n\n- $and, $or, $not, $nor\n\n```js\n// {$and : [{},{}]}\nconst products = await Product.find({\n  $and: [{ price: { $lt: 1400 } }, { rating: { $gt: 4 } }],\n});\n\nconst products = await Product.find({\n  $or: [{ price: { $lt: 1400 } }, { rating: { $gt: 4 } }],\n});\n\n// returns all that fail both clauses\nconst products = await Product.find({\n  $nor: [{ price: { $lt: 1400 } }, { rating: { $gt: 4 } }],\n});\n\n// $not\nconst products = await Product.find({ price: { $not: { $lt: 900 } } });\n```\n\n## 14. counting and sorting\n\n- countDocuments() / count()\n\n```js\nconst products = await Product.find({ price: { $gt: 900 } }).countDocuments();\n\n// ascending\nconst products = await Product.find().sort({ price: 1 });\n\n// descending\nconst products = await Product.find().sort({ price: -1 });\n\n// sort and select\nconst products = await Product.find()\n  .sort({ title: 1 })\n  .select({ title: 1, _id: 0 });\nconsole.log(products);\n```\n\n## 15. update data\n\n- update data syntax: `db.collectionName.updateOne(selection_item, update_data)`\n- update data syntax: `db.collectionName.findByIdAndUpdate(selection_item, update_data, {new: true})`\n\n```js\n// updateOne\nconst products = await Product.updateOne({ _id }, { $set: { rating: 4.8 } });\nconsole.log(products);\nupdateProduct(\"63432689c564aea397b3d210\");\n\n// findByIdAndUpdate it returns old data\nconst products = await Product.findByIdAndUpdate(\n  { _id },\n  { $set: { rating: 4.8 } }\n);\nconsole.log(products);\n\n// findByIdAndUpdate it returns updated data\nconst products = await Product.findByIdAndUpdate(\n  { _id },\n  { $set: { rating: 4.7 } },\n  { new: true }\n);\nconsole.log(products);\n```\n\n## 16. delete data\n\n- example: `db.users.deleteOne({name:\"anisul islam\"})`\n\n```js\nconst products = await Product.deleteOne({ _id });\nconsole.log(products);\n\n// findByIdAndDelete return deleted data\nconst products = await Product.findByIdAndDelete({ _id });\nconsole.log(products);\n```\n\n## 17. mongoose validations\n\n- [official documentation](https://mongoosejs.com/docs/validation.html)\n- A common gotcha for beginners is that the unique option for schemas is not a validator.\n- Numbers have: min, max validators\n- Strings have: minlength, maxlength, trim, lowercase, enum\n- validator error message can be provided using array syntax and object syntax\n\n```js\nArray syntax: min: [6, 'Must be at least 6, got {VALUE}']\nObject syntax: enum: { values: ['Coffee', 'Tea'], message: '{VALUE} is not supported' }\n```\n\n```js\n// validation when creating schema\n  title: {\n    type: String,\n    required: [true, \"product title is required\"],\n\n    minlength: 3,\n    minlength: [3, \"error message here\"],\n    maxlength: 3,\n\n    lowercase: true,\n    uppercase: true,\n\n    trim: true // \"     iphone 7      \",\n    enum: [\"iphone\", \"samsung\", \"motorola\"] // no other value is allowed other than these,\n    enum: {\n      values: ['iphone', 'samsung', motorola\"],\n      message: '{VALUE} is not supported'\n    }\n  },\n  price:{\n     type: String,\n     required: true,\n     min: 20,\n     max: 30\n  }\n\n\n```\n\n## 18. Custom validations\n\n- for fulfilling own requirements based on certain situation we need to create custom validations.\n- read about email vliadation\n- [create your own validation regular expression](https://regexr.com/3e48o)\n\n```js\nprice:{\n    type: String,\n    required: [true, \"title is required\"],\n    validate: {\n      validator: function (v) {\n        return v.length === 10;\n      },\n      message: (props) =\u003e `${props.value} is not a valid product title!`,\n    },\n},\nphone: {\n    type: String,\n    validate: {\n      validator: function(v) {\n        return /\\d{3}-\\d{3}-\\d{4}/.test(v);\n      },\n      message: props =\u003e `${props.value} is not a valid phone number!`\n    },\n    required: [true, 'User phone number required']\n  }\n  email:{\n    // ^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$\n    type: String,\n    required: [true, 'User email is required'],\n    trim: true,\n    lowercase: true,\n    unique: true,\n    validate: {\n      validator: function(v) {\n        const emailRegex = /^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$/;\n        return emailRegex.test(v);\n      },\n      message: props =\u003e `${props.value} is not a valid phone number!`\n    },\n     email: {\n        type: String,\n        trim: true,\n        lowercase: true,\n        unique: true,\n        required: 'Email address is required',\n        validate: [validateEmail, 'Please fill a valid email address'],\n        match: [/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/, 'Please fill a valid email address']\n    }\n\n  }\n```\n\n## 19. npm validator\n\n- `npm i validator`\n\n```js\nemail: {\n    type: String,\n    unique: true,\n    required: [true, \"email is required\"],\n    trim: true,\n    lowercase: true,\n    validate: {\n      validator: validator.isEmail,\n      message: (props) =\u003e `${props.value} is not a valid email!`,\n    },\n  },\n```\n\n## 20. pagination\n\n```js\nconst { page = 1, limit = 10 } = req.query;\nconst products = await Product.find()\n  .limit(limit)\n  .skip((page - 1) * limit);\nconsole.log(products);\n```\n\n## Follow Me\n\n\u003cimg src =\"https://www.edigitalagency.com.au/wp-content/uploads/Facebook-logo-blue-circle-large-transparent-png.png\" height=\"15px\" width=\"15px\"/\u003e [Facebook](http://facebook.com/learnwithfair), \u003cimg src =\"https://image.similarpng.com/very-thumbnail/2021/10/Youtube-icon-design-on-transparent-background-PNG.png\" height=\"20px\" width=\"20px\"/\u003e [Youtube](http://youtube.com/@learnwithfair), \u003cimg src =\"https://i.pinimg.com/originals/fa/ea/02/faea02f412415becfb4939d2b6431c28.jpg\" height=\"15px\" width=\"15px\"/\u003e [Instagram](http://instagram.com/learnwithfair)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fmongodb-documentation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearnwithfair%2Fmongodb-documentation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fmongodb-documentation/lists"}