Skip to content

Commit

Permalink
update mongo pages
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelCurrin authored Aug 9, 2024
1 parent f74717d commit 9f60436
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 124 deletions.
22 changes: 0 additions & 22 deletions cheatsheets/nosql/mongodb/advanced-features.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,5 @@
# Advanced Features

MongoDB provides several advanced features, including:

## Indexing

Indexes can significantly improve query performance by allowing MongoDB to quickly locate relevant documents.

```console
> db.users.createIndex({ name: 1 })
```

## Aggregation

MongoDB's aggregation framework allows you to perform complex data processing and analysis operations on your data.

```console
> db.users.aggregate([
{ $match: { age: { $gt: 30 } } },
{ $group: { _id: '$city', count: { $sum: 1 } } }
])
```

## Replication

Replication allows you to create redundant copies of your data across multiple servers, providing high availability and fault tolerance.
Expand All @@ -33,4 +12,3 @@ Sharding is a horizontal scaling technique that allows you to distribute data ac

MongoDB supports multi-document transactions, allowing you to perform multiple operations as an all-or-nothing unit of work.

Sure, here's a short section on how to create related collections in MongoDB, using the example of Users and Posts:
148 changes: 121 additions & 27 deletions cheatsheets/nosql/mongodb/basic-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,147 @@

## Creating a Database

In MongoDB, databases are created implicitly when you create your first collection or document. You can switch to a specific database using the `use` command:
Databases are created implicitly when you create your first collection or document.

```console
> use myapp
switched to db myapp
You can switch to a specific database using the `use` command:

```javascript
use myapp
```

## Create a collection

Collections are analogous to tables in relational databases.

```javascript
db.createCollection("users")
```

## Creating a Collection
## Insert document

The collection will be created if it does not yet exist.

Use `insertOne` for inserting a single document.
```javascript
db.products.insertOne( { _id: 10, item: "box", qty: 20 } );
```

Use `insertMany` for inserting multiple documents with atomicity guarantees

```javascript
db.users.insertMany(
[
{ name: 'John Doe', email: 'john@example.com' },
{ name: 'Jane Doe', email: 'jane@example.com' }
]
)
```

Use `insert` only if you need to insert multiple documents and can handle partial failures.

```javascript
// One
db.users.insert({ name: 'John Doe', email: 'john@example.com' })
// Multiple
db.users.insert(
[
{ name: 'John Doe', email: 'john@example.com' },
{ name: 'Jane Doe', email: 'jane@example.com' }
]
)
```

## Query documents

You can query documents using the `find` method for a list or `findOne` for one record.

Collections are analogous to tables in relational databases. You can create a collection by inserting your first document into it:
Without a filter:

```console
> db.users.insert({ name: 'John Doe', email: 'john@example.com' })
WriteResult({ "nInserted" : 1 })
```javascript
db.users.find()
[
{
_id: ObjectId('66b5d739dd67dbed4f2e4df7'),
name: 'John Doe',
email: 'john@example.com'
}
]
```

This command creates a new collection named `users` and inserts a document into it.
With a filter:

## Querying Documents
```javascript
db.users.find({ age: { $gt: 30 } })
```

You can query documents using the `find` method:
Assign to a variable:

```console
> db.users.find()
{ "_id" : ObjectId("6436e9c8d9f6b3c8e7f9d9e3"), "name" : "John Doe", "email" : "john@example.com" }
```javascript
var user = db.users.findOne(...)
```

You can also filter documents using query operators:
Iterate over results:

```console
> db.users.find({ age: { $gt: 30 } })
```javascript
var users = db.users.find();
while (users.hasNext()) {
print(users.next());
}
```

## Updating Documents
## Update documents

You can update documents using the `update` method:
You can update documents using the `update` method. If the field does not exist, it will be added.

```console
> db.users.update({ name: 'John Doe' }, { $set: { email: 'john.doe@example.com' } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
```javascript
db.users.update(
{ name: 'John Doe' },
{
$set: {
email: 'john.doe@example.com',
age: 31
}
}
)
```

## Deleting Documents
## Delete documents

You can delete documents using the `remove` method:

```console
> db.users.remove({ name: 'John Doe' })
WriteResult({ "nRemoved" : 1 })
```javascript
db.users.deleteOne({ name: 'John Doe' })
```


## Indexing

Indexes can significantly improve query performance by allowing MongoDB to quickly locate relevant documents.

Create an index on `name` field of the users collection, using ascending order with `1`.

```javascript
> db.users.createIndex({ name: 1 })
```

See the [createIndex docs](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex/) for syntax.

## Aggregation

MongoDB's aggregation framework allows you to perform complex data processing and analysis operations on your data.

```javascript
db.users.aggregate([
{ $group: { _id: '$city', count: { $sum: 1 } } }
])
// [ { _id: null, count: 3 } ]
```

With a filter:

```javascript
db.users.aggregate([
{ $match: { age: { $gt: 30 } } },
{ $group: { _id: '$city', count: { $sum: 1 } } }
])
```
6 changes: 5 additions & 1 deletion cheatsheets/nosql/mongodb/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,8 @@ For a cloud deployment, you can use connection string. Example based on the docs

```sh
$ mongosh "mongodb+srv://mycluster.abcd1.mongodb.net/myFirstDatabase" --apiVersion 1 --username <username>
```
```

Then use the `help` command in the interactive shell for commands. See also the [Basic operations][] cheatsheet.

[Basic operations]: {% link cheatsheets/nosql/mongodb/basic-operations.md %}
92 changes: 18 additions & 74 deletions cheatsheets/nosql/mongodb/related-collections.md
Original file line number Diff line number Diff line change
@@ -1,104 +1,48 @@
# Related Collections
# Related collections

MongoDB's flexible schema allows you to represent relationships between data in different ways. One common approach is to use separate collections for related entities and establish relationships using references or embedded documents.

## Users and Posts

Let's consider an example where we have a `users` collection and a `posts` collection, representing user profiles and blog posts, respectively.

### Sample of related data

### Create

```javascript
// users collection
{
"_id": ObjectId("6436e9c8d9f6b3c8e7f9d9e3"),
db.users.insertOne({
"_id": 2,
"name": "John Doe",
"email": "john@example.com"
}
})

// posts collection
{
"_id": ObjectId("6436e9c8d9f6b3c8e7f9d9e4"),
db.posts.insertOne({
"_id": 2,
"title": "My First Post",
"content": "This is the content of my first blog post.",
"author": ObjectId("6436e9c8d9f6b3c8e7f9d9e3"),
"author": 2,
"comments": [
{
"author": ObjectId("6436e9c8d9f6b3c8e7f9d9e5"),
"content": "Great post!",
"timestamp": ISODate("2023-04-11T10:30:00Z")
}
]
}
```

In this example, we have separate collections for `users` and `posts`. The `posts` collection contains an `author` field that references the `_id` of the corresponding user document in the `users` collection. Additionally, the `comments` field in the `posts` collection is an array of embedded documents, where each comment references the `_id` of the user who posted the comment.

This approach allows you to query and update users and posts independently while maintaining the relationship between them. You can use MongoDB's query operators and aggregation framework to perform complex operations involving related data.

### Create collections

To create these related collections, you can use the `db.createCollection()` method in the MongoDB shell or the appropriate driver method in your programming language of choice.

```javascript
// Create the users collection
db.createCollection("users")

// Create the posts collection
db.createCollection("posts")
})
```

Once the collections are created, you can insert documents and establish relationships between them using references or embedded documents, as shown in the example above.

This is just one way to represent relationships in MongoDB. Depending on your data model and requirements, you may choose to use different approaches, such as embedding documents within other documents or using more advanced techniques like application-level joins or data denormalization.
### Find

### Get all posts for a user

To get all posts for a specific user, you can use the `find` method and filter the `posts` collection based on the `author` field, which references the user's `_id`.
Get a post for a specific user.

```javascript
// Get the user's _id
var userId = ObjectId("6436e9c8d9f6b3c8e7f9d9e3");

// Find all posts where the author field matches the user's _id
db.posts.find({ author: userId });
db.posts.find({ "author": 1})
```

This query will return all documents in the `posts` collection where the `author` field matches the provided `userId`.

### Get a user given a comment

To get the user who posted a specific comment, you can use the `$unwind` operator to deconstruct the `comments` array in the `posts` collection, and then perform a lookup to the `users` collection based on the `author` field in the comment document.
Find comments for a specifc user, returning comments data only for a post:

```javascript
// Get the comment's author _id
var commentAuthorId = ObjectId("6436e9c8d9f6b3c8e7f9d9e5");

// Find the user document based on the comment author _id
db.posts.aggregate([
{ $unwind: "$comments" },
{ $match: { "comments.author": commentAuthorId } },
{
$lookup: {
from: "users",
localField: "comments.author",
foreignField: "_id",
as: "commentAuthor"
}
},
{ $unwind: "$commentAuthor" },
{ $project: { _id: 0, commentAuthor: 1 } }
]);
db.posts.find(
{ "author": 1 },
{ "comments": 1, "_id": 0 }
)
```

Here's what this query does:

1. `$unwind`: Deconstructs the `comments` array, creating a separate document for each comment.
2. `$match`: Filters the documents to only include those where the `author` field in the comment matches the provided `commentAuthorId`.
3. `$lookup`: Performs a left outer join with the `users` collection, matching the `author` field in the comment with the `_id` field in the `users` collection. The matched user documents are stored in the `commentAuthor` field.
4. `$unwind`: Deconstructs the `commentAuthor` array, which should contain at most one document.
5. `$project`: Excludes the `_id` field and includes only the `commentAuthor` field, which contains the user document for the comment author.

This query will return the user document for the author of the specified comment.

Note that these queries assume that you have properly set up the relationships between the `users` and `posts` collections using references or embedded documents, as shown in the previous example.

0 comments on commit 9f60436

Please sign in to comment.