MongoDB cheat sheet/crash course
Tags: webdev, mongodb, beginners, javascript
Published: 2022-12-24 21:04:13

> 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.

```js
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.

```js
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.

```js
db.users.find()
```
`find(<filterObject>)`: Find all documents based on the filter object

```js
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

```js
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.

```js
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.

```js
db.users.countDocuments({ name: “Arafat” })
// Get the number of users with the name Arafat
```

## Update
`updateOne`: Updates the first document.

```js
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.

```js
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.

```js
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.

```js
db.users.deleteOne({ name: "Arafat" })
// Delete the first user with an name of Arafat
```

`deleteMany`: Delete multiple documents from a collection.

```js
db.users.deleteMany({ age: 26 })
// Delete all users with an age of 26
```

## Complex Filter Object
`$eq`: equals.

```js
db.users.find({ name: { $eq: “Arafat” } })
// Get all the users with the name Arafat
```

`$ne`: not equal to.

```js
db.users.find({ name: { $ne: “Arafat” } })
// Get all users with a name other than Kyle
```

`$gt / $gte`: Greater than and greater than or eqal.

```js
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.

```js
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.

```js
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.

```js
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

```js
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

```js
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

```js
db.users.find({ name: { $not: { $eq: “Arafat” } } })
Get all users with a name other than Arafat
```

`$exists`: Matches documents that have the specified field.

```js
db.users.find({ name: { $exists: true } })
// Returns all users that have a name field
```

`$expr`: performs an expression evaluation in the query.

```js
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`.

```js
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.

```js
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

```js
db.users.updateMany({}, { $rename: { loss: “Profit” } })
// Rename the field loss to profit for all users
```

`$unset`: Remove a field.

```js
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

```js
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.

```js
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.

```js
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.

```js
db.users.find().limit(5)
// Returns the first 5 users
```

`skip`: Skip a specified number of documents from the start.

```js
db.users.find().skip(7)
// Skip the first 7 users when returning results. Freat for pagination when combined with limit.
```