MongoDB cheat sheet/crash course
Arafat
Posted on December 24, 2022
Here is a cheat sheet for
mongodb
Basic Idea
Database:
A container of collection.
Collection
: Grouping of documents insida of a database. Similar tables in SQL.
Document
: A record inside of a collection. Similar to row in SQL.
Field
: A key value pair within a document. Similar to column in SQL.
Basic commands
mongosh
: A JavaScript shell for interacting with MongoDB instances. It provides a command-line interface (CLI) that allows you to connect to a MongoDB server.
show dbs
: Shows all databases in the current MongoDB instance.
use <dbname>
: Switch database provided by dbname.
db
: Shows current database name.
show collections
: Shows all collections.
db.dropDatabase()
: Deletes the current database.
exit
: Exits the mongosh session.
Create
insertOne
: Creates a document within the specified collection.
db.users.insertOne({ name: “Arafat” })
// Create a document with the name of Arafat into the users collection
insertMany
: Creates multiple documents within the specified collection.
db.users.insertMany([{ name: “John” }, { age: “Roy” }])
// Create two documents with the name John and Roy into the users collection
Read
find
: Get all documents.
db.users.find()
find(<filterObject>)
: Find all documents based on the filter object
db.users.find({ name: “Arafat” })
// Get all users with the name Arafat
db.users.find({ “address.street”: “434 Lund Sweden” })
// Get all users whose adress field has a street field with the value 434 Lund Sweden
find(<filterObject>, <selectObject>)
: Find all documents that match the filter object but only return the field specified in the select object
db.users.find({ name: “Arafat” }, { name: 1, hobby: 1 })
// Get all users with the name Arafat but only return their name, hobby, and _id
db.users.find({}, { hobby: 0 })
// Get all users and return all fields except for hobby
findOne
: Returns the first document that matches the filter object.
db.users.findOne({ name: “Arafat” })
// Get the first user with the name Arafat
countDocuments
: Returns the count of the documents that match the filter object.
db.users.countDocuments({ name: “Arafat” })
// Get the number of users with the name Arafat
Update
updateOne
: Updates the first document.
db.users.updateOne({ name: "Arafat" }, { $set: { name: "Theo" } })
// Update the first user with a name of Arafat to the name of Theo
updateMany
: Updates multiple docments.
db.users.updateMany({ age: 16 }, { $inc: { age: 6 } })
// Update all users with an age of 16 by adding 6 to their age
replaceOne
: Replace the first document. This
will completely overwrite the entire object and not just
update individual fields.
db.users.replaceOne({ age: 12 }, { age: 13 })
// Replace the first user with an age of 12 with an object that has the age of 13 as its only field
Delete
deleteOne
: Delete a single document from a collection.
db.users.deleteOne({ name: "Arafat" })
// Delete the first user with an name of Arafat
deleteMany
: Delete multiple documents from a collection.
db.users.deleteMany({ age: 26 })
// Delete all users with an age of 26
Complex Filter Object
$eq
: equals.
db.users.find({ name: { $eq: “Arafat” } })
// Get all the users with the name Arafat
$ne
: not equal to.
db.users.find({ name: { $ne: “Arafat” } })
// Get all users with a name other than Kyle
$gt / $gte
: Greater than and greater than or eqal.
db.users.find({ age: { $gt: 26 } })
// Get all users with an age greater than 26
db.users.find({ age: { $gte: 34 } })
// Get all users with an age greater than or equal to 34
$lt / $lte
: Less than and less than or eqal.
db.users.find({ age: { $lt: 26 } })
// Get all users with an age less than 26
db.users.find({ age: { $lte: 34 } })
// Get all users with an age less than or equal to 34
$in
: Check if a value is one of many values.
db.users.find({ name: { $in: [“Roy”, “Leo”] } })
// Get all users with a name of Roy or Leo
$nin
: Check if a value is none of many values.
db.users.find({ name: { $nin: [“Roy”, “Leo”] } })
// Get all users that do not have the name Roy or Leo
$and
: Returns true if all expressions are true
db.users.find({ $and: [{ age: 6 }, { name: “Arafat” }] })
// Get all users that have an age of 6 and the name Arafat
db.users.find({ age: 6, name: “Arafat” })
// Alternative way to do same thing
$or
: returns true if any expression is true
db.users.find({ $or: [{ age: 6 }, { name: “Arafat” }] })
// Get all users that have an age of 6 or the name Arafat
$not
: Negates the expression
db.users.find({ name: { $not: { $eq: “Arafat” } } })
Get all users with a name other than Arafat
$exists
: Matches documents that have the specified field.
db.users.find({ name: { $exists: true } })
// Returns all users that have a name field
$expr
: performs an expression evaluation in the query.
db.users.find({ $expr: { $gt: [“$balance”, “$debt”] } })
// Get all users that have a balance that is greater than their debt
Complex Update Object
$set
: Updates only the fields passed to $set
.
db.users.updateOne({ age: 12 }, { $set: { name: “Roy” } })
// Update the name of the first user with the age of 12 to the value Roy
$inc
: Increments the value of a field by a specified amount.
db.users.updateOne({ debt: 200 }, { $inc: { debt: 100 } })
// Add 100 to the debt of the first user with the debt of 200
db.users.updateOne({ debt: 200 }, { $inc: { debt: -100 } })
// Remove 100 from the debt of the first user with the debt of 200
$rename
: Rename a field
db.users.updateMany({}, { $rename: { loss: “Profit” } })
// Rename the field loss to profit for all users
$unset
: Remove a field.
db.users.updateOne({ age: 26 }, { $unset: { age: "" } })
// Remove the age field from the first user with an age of 26
$push
: Adds new elements to an array
db.users.updateMany({}, { $push: { enemy: “Ria” } })
// Add Ria to the enemy array for all users
$pull
: Rmoves all array elements that match a specified condition.
db.users.updateMany({}, { $pull: { enemy: “Arafat” } })
// Remove Mike from the friends array for all users
Modifiers for read
sort
: Sort the results of a find
by the given fields.
db.users.find().sort({ debt: 1, balance: -1 })
// Returns all users sorted by name in alphabetical order and then if any duplicated names exits, sorts by age in reverse order.
limit
: Returns a specified number of documents.
db.users.find().limit(5)
// Returns the first 5 users
skip
: Skip a specified number of documents from the start.
db.users.find().skip(7)
// Skip the first 7 users when returning results. Freat for pagination when combined with limit.
Posted on December 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 25, 2024