diff --git a/cheatsheets/nosql/mongodb/advanced-features.md b/cheatsheets/nosql/mongodb/advanced-features.md index 1e1f37ed5..bac480e7e 100644 --- a/cheatsheets/nosql/mongodb/advanced-features.md +++ b/cheatsheets/nosql/mongodb/advanced-features.md @@ -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. @@ -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: diff --git a/cheatsheets/nosql/mongodb/basic-operations.md b/cheatsheets/nosql/mongodb/basic-operations.md index 3b85748e0..49796fb8c 100644 --- a/cheatsheets/nosql/mongodb/basic-operations.md +++ b/cheatsheets/nosql/mongodb/basic-operations.md @@ -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 } } } +]) ``` diff --git a/cheatsheets/nosql/mongodb/cli.md b/cheatsheets/nosql/mongodb/cli.md index 239a8ac4a..9df679825 100644 --- a/cheatsheets/nosql/mongodb/cli.md +++ b/cheatsheets/nosql/mongodb/cli.md @@ -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 -``` \ No newline at end of file +``` + +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 %} \ No newline at end of file diff --git a/cheatsheets/nosql/mongodb/related-collections.md b/cheatsheets/nosql/mongodb/related-collections.md index 02c2f4a27..fac27c1ea 100644 --- a/cheatsheets/nosql/mongodb/related-collections.md +++ b/cheatsheets/nosql/mongodb/related-collections.md @@ -1,4 +1,4 @@ -# 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. @@ -6,99 +6,43 @@ MongoDB's flexible schema allows you to represent relationships between data in 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.