Let's talk about MongoDB - The database for modern applications
MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud era. No database makes you more productive.
Installation
These Links provide instructions to install MongoDB Community Edition for supported Linux systems.
These Links provide instructions to install MongoDB Community Edition for macOS systems.
These Links provide instructions to install MongoDB Community Edition for Windows systems.
Basic MongoDB commands
Open your terminal
, command prompt
, power shell
or bash
. Whichever you have installed on your system and let's get started
To start the MongoDB shell,
mongo
Will create a database named amazon and switch to it
use amazon
Will show you the current database you're in
db
Will display all databases you have
show dbs
Will create a collection called
products
with documentsname
andmacbook
value in the amazon databasedb.products.insert({name: "macbook"})
Will create a collection of users
db.createCollection("users")
Will show a list of collections in your database
show collections
Will delete the collection users from the database
db.users.drop()
Will delete the entire database you are currently on
db.dropDatabase()
Creates a collection products and inserts one document into it
db.products.insertOne({name: "macbook", price: 1500, category: "Computers"})
Will help us find all the documents in the products collection
db.products.find()
Will creates many documents into the product collection
db.products.insertMany([{name: "iPhone 11", price: 1900, category: " Electronics"}, {name: "Headphone", price: 120, category: "Electronics" }])
Reading (flittering) query's from MongoDB
The
find()
helps us find every document in a collection e.g in products belowdb.products.find()
Returns the
collection
results in JSON formatdb.products.find().pretty()
Finds a specific item passed in, if it exists
db.products.find({name: "macbook"})
Finds a specific key only
db.products.find({}, {name: 1})
Finds a specific key only and hide the _id
db.products.find({}, {name: 1, _id: 0})
Finds a specific key only, hide the _id and show only the first 2
db.products.find({}, {name: 1, _id:0}).limit(2)
Finds every item that is
less than
150db.products.find({price : {$lt: 150} })
Finds every item that is
less than
orequal to
150db.products.find({price : {$lte: 150} })
Finds every item that is
grater than
800db.products.find({price : {$gt: 800} })
Finds every item that is
grater than
orequal to
800db.products.find({price : {$gte: 800} })
Finds every item that its price is
less than
200and
belongs to the category ofElectronics
db.products.find({$and: [{price: {$lt:200}}, {category: "Electronics"} ]})
Finds every item that its price is
greater than
500or
belongs to the category ofElectronics
db.products.find({$or: [{price: {$gt:500}}, {category: "Electronics"} ]})
Bonus
Click HERE to download PDF version of this tutorial