Rajat Saxena
July 9, 2023
MongoDB is a Document database used by companies like Forbes, Toyota etc. CourseLit (CodeLit’s own LMS) also uses MongoDB as a database.
All the database operations are going to use the following data. It is a list of hotels.
[
{
"name": "Blue Royal",
"price": 200,
"amenities": ["tv", "geyser", "wifi"],
"address": {
"city": "Mumbai"
}
},
{
"name": "Panama Lagoon",
"price": 300,
"amenities": ["tv", "wifi"],
"address": {
"city": "Bangalore"
}
},
{
"name": "Ibis Luxuries",
"price": 650,
"amenities": ["tv", "geyser", "wifi", "meals"],
"address": {
"city": "Mumbai"
}
},
{
"name": "Paris Knight",
"price": 450,
"amenities": ["tv", "meals"],
"address": {
"city": "New Delhi"
}
},
{
"name": "Citrus Hotel",
"price": 150,
"amenities": [],
"address": {
"city": "New Delhi"
}
}
]
Install Mongosh.
Connect using the following command.
mongosh <connection-string>
To obtain a connection string of your MongoDB Atlas instance, go here.
show databases
use <database-name>
show collections
db.hotels.insertOne({
"name": "Blue Royal",
"price": 200,
"amenities": ["tv", "geyser", "wifi"],
"address": {
"city": "Mumbai"
}
});
db.hotels.insertMany([
{
"name": "Panama Lagoon",
"price": 300,
"amenities": ["tv", "wifi"],
"address": {
"city": "Bangalore"
}
},
{
"name": "Ibis Luxuries",
"price": 650,
"amenities": ["tv", "geyser", "wifi", "meals"],
"address": {
"city": "Mumbai"
}
},
{
"name": "Paris Knight",
"price": 450,
"amenities": ["tv", "meals"],
"address": {
"city": "New Delhi"
}
},
{
"name": "Citrus Hotel",
"price": 150,
"amenities": [],
"address": {
"city": "New Delhi"
}
}
])
db.hotels.drop()
db.hotels.find()
db.hotels.find({ name: "Paris Knight" })
db.hotels.find({}, {name: 1})
// skip _id field as well
db.hotels.find({}, {name: 1, _id: 0})
// Get only one record
db.hotels.find().limit(1)
// Sort by price 'low to high'
db.hotels.find().sort({price: 1})
db.hotels.countDocuments()
db.hotels.find({price: {$lt: 300}})
db.hotels.find({"address.city": "Mumbai"})
db.hotels.find({"address.city": {$in: ["New Delhi", "Mumbai"]}})
db.hotels.find({amenities: {$all: ["tv", "geyser"]}})
db.hotels.find({amenities: {$all: ["tv", "wifi"]}, price: {$gt: 200}})
See the list of all operators here.
db.hotels.updateOne(
{name: "Blue Royal"},
{$set: {price: 250}}
);
db.hotels.update(
{name: "Ibis Luxuries"},
{$set: {"address.country": "india"}}
)
db.hotels.updateOne(
{name: "Ibis Luxuries"},
{$addToSet: {amenities: "spa"}}
);
db.hotels.updateOne(
{name: "Ibis Luxuries"},
{$pull: {amenities: "spa"}}
);
db.hotels.update(
{name: "Ibis Luxuries"},
{$unset: {"address.country": ""}}
)
db.hotels.updateMany({}, {$inc: {price: 20}})
If a matching record is not found, it will be inserted instead.
db.hotels.update(
{name: "Gloria Paradise"},
{$set: {price: 350, amenities: ["tv"]}},
{upsert: true}
)
db.hotels.deleteOne({name: 'Gloria Paradise'})
db.hotels.deleteMany({"address.city": "New Delhi"})
db.hotels.deleteMany({})