MongoDB
- MongoDB is a document database designed for ease of development and scaling.
- It is intuitive and easy to use NoSQL Database.
- Available as community and enterprise edition.
“mongo” is the command line shell that connects to a specific instance of mongod
“mongod” is the “Mongo Daemon” it’s basically the host process for the database.
MongoDB internally uses BSON, because BSON is very efficient compared to JSON. In MongoDB instead of tables like SQL it has collections, and rows are known as documents.
In MongoDB the key: value pair of each document is called field: value
Install: for personal use you going to install MongoDB Community Version with Community server. While installing always make sure to have checkbox option is clicked for run mongod as a service
Always make sure to add the path if working on the Windows Machine.
Go to directory where MongoDB is installed = MongoDB->Server->4.4(Version)->bin-> add to path. To run the executables of the MongoDB.
MongoDB Compass
Most Common Commands for MongoDB
Database Command
- View all databases
show dbs
- Create a new or switch databses
use dbName
- View current database
db
- Delete databse
db.dropDatabase()
Collection Commands
- Show Collections
show collections
- Create a collection named “name”
db.createCollection(‘name’)
- Drop a collection named “name”
db.name.drop()
Row(Document) Commands
- Show all rows in a collection
db.name.find()
- Show all rows in a collection(prettified)
db.name.find().pretty()
- Find the first row matching the object
db.name.findOne({name: ‘Shubham’})
- Insert one row
db.name.insert({ ‘name’: ‘Shubham’, ‘lang’: ‘Python’, ‘member’: ‘Student })
- Insert many rows
db.name.insertMany([{ ‘name’: ‘Shubham’, ‘lang’: ‘Python’, ‘member’: ‘Student }, { ‘name’: ‘Shubh’, ‘lang’: ‘C++’, ‘member’: ‘Student }, { ‘name’: ‘Shubhammm’, ‘lang’: ‘Java’, ‘member’: ‘Student }])
- Search in MongoDB Database
db.name.find({‘lang’: ‘Java’})
- Limit the number of rows in output
db.name.find().limit(2)
- Count the number of rows in the output
db.name.find().count()
- Update a row
db.name.update({name: ‘Shivam’}, {‘name’: ‘Shubham’, ‘lang’: ‘Python’, ‘member’: ‘Student }, {upsert: true})
- Mongodb Increment Operator
db.name.update({name: ‘Shubham’}, { $inc:{ member: 22 } })
- Rename Operator
db.name.update({name:’Shubham’}, {$rename:{ member: ‘mem’ }})
- Delete row
db.name.remove({name: ‘Shubham})
- Less than/Greater than/ Less than or Equal/Greater than or Equal
db.name.find({member: {$lt: 90}}) db.name.find({member: {$lte: 90}}) db.name.find({member: {$gt: 90}}) db.name.find({member: {$gte: 90}})