mirror of
https://github.com/kamranahmedse/developer-roadmap.git
synced 2025-08-31 21:11:44 +02:00
Migrate MongoDB roadmap
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
# Aggregation
|
||||
|
||||
Aggregation in MongoDB is a powerful framework for data processing and transformation using a pipeline of stages. Each stage performs specific operations like filtering, grouping, sorting, or computing values, allowing complex data analytics and reporting. The aggregation pipeline offers operators for mathematical calculations, string manipulation, date operations, and advanced data transformations.
|
@@ -0,0 +1,3 @@
|
||||
# $all
|
||||
|
||||
The $all operator in MongoDB selects documents where an array field contains all specified elements, regardless of order or additional elements. It's useful for tag-based filtering and ensuring multiple required values exist in arrays. $all performs element-wise matching and can work with arrays of different data types, making it essential for multi-criteria array filtering.
|
@@ -0,0 +1,3 @@
|
||||
# $and
|
||||
|
||||
The $and operator in MongoDB performs logical AND operation on multiple query expressions, returning documents that satisfy all specified conditions. It accepts an array of query expressions and is implicitly used when multiple conditions are provided at the same level. $and is explicit when combining complex expressions or when the same field needs multiple conditions.
|
@@ -0,0 +1,3 @@
|
||||
# Array
|
||||
|
||||
Array data type in MongoDB stores ordered lists of values including mixed data types, nested arrays, and embedded documents. Arrays support indexing with multikey indexes, enabling efficient queries on array elements. Special array operators like $push, $pull, $addToSet modify arrays, while query operators like $in, $all, $elemMatch enable sophisticated array querying and element matching capabilities.
|
@@ -0,0 +1,3 @@
|
||||
# Atlas Search Indexes
|
||||
|
||||
Atlas Search indexes in MongoDB Atlas provide full-text search capabilities using Apache Lucene technology. They enable sophisticated text search with relevance scoring, autocomplete, faceted search, and synonyms. These indexes support complex search queries across multiple fields, fuzzy matching, and advanced text analysis features for building modern search experiences in applications.
|
@@ -0,0 +1,3 @@
|
||||
# Binary Data
|
||||
|
||||
Binary data in MongoDB stores non-textual data like images, files, and encoded content using the BSON Binary data type. It supports various subtypes including generic binary, function code, UUID, and MD5 hashes. Binary data enables efficient storage of multimedia content, encrypted data, and arbitrary byte sequences while maintaining query and indexing capabilities within document structures.
|
@@ -0,0 +1,3 @@
|
||||
# Boolean
|
||||
|
||||
Boolean data type in MongoDB stores true or false values, representing logical states in documents. Booleans are commonly used for flags, status indicators, and conditional logic in queries and applications. They support direct comparison, logical operations with $and, $or, $not operators, and can be efficiently indexed for fast querying of true/false conditions in large datasets.
|
@@ -0,0 +1,3 @@
|
||||
# BSON vs JSON
|
||||
|
||||
BSON (Binary JSON) is MongoDB's binary-encoded serialization format that extends JSON with additional data types like dates, binary data, and 64-bit integers. While JSON is human-readable text format, BSON provides faster parsing, compact storage, and native support for MongoDB's rich data types. BSON enables efficient storage and retrieval while maintaining JSON's flexibility and document structure.
|
@@ -0,0 +1,3 @@
|
||||
# bulkWrite() and Related Methods
|
||||
|
||||
bulkWrite() in MongoDB performs multiple write operations in a single command, improving performance through reduced network round trips. It supports mixed operations including inserts, updates, deletes, and replaces with options for ordered or unordered execution. Bulk operations provide error handling, write concern configuration, and significant performance benefits for high-volume data manipulation tasks.
|
@@ -0,0 +1,3 @@
|
||||
# Client-Side Field Level Encryption
|
||||
|
||||
Client-Side Field Level Encryption (CSFLE) allows applications to encrypt sensitive data fields before storing them in MongoDB. The database receives only encrypted data and remains unaware of the encryption keys, ensuring zero-trust security. This feature provides deterministic and randomized encryption algorithms, enabling both exact match queries and enhanced security for highly sensitive information.
|
@@ -0,0 +1,3 @@
|
||||
# Collection Methods
|
||||
|
||||
Collection methods in MongoDB provide comprehensive operations for data manipulation including CRUD operations (find, insert, update, delete), index management, and administrative functions. Key methods include createIndex(), drop(), count(), distinct(), and bulkWrite() for batch operations. These methods offer flexible options for data processing, schema validation, and collection maintenance.
|
@@ -1,43 +0,0 @@
|
||||
# bulkWrite() and others
|
||||
|
||||
Bulk write operations allow you to perform multiple create, update, and delete operations in a single command, which can significantly improve the performance of your application. MongoDB provides two types of bulk write operations:
|
||||
|
||||
- **Ordered Bulk Write**: In this type of bulk operation, MongoDB executes the write operations in the order you provide. If a write operation fails, MongoDB returns an error and does not proceed with the remaining operations.
|
||||
|
||||
- **Unordered Bulk Write**: In this type of bulk operation, MongoDB can execute the write operations in any order. If a write operation fails, MongoDB will continue to process the remaining write operations.
|
||||
|
||||
To perform a bulk write operation, use the `initializeOrderedBulkOp()` or `initializeUnorderedBulkOp()` methods to create a bulk write object.
|
||||
|
||||
## Example: Ordered Bulk Write
|
||||
|
||||
Here's an example of an ordered bulk write operation:
|
||||
|
||||
```javascript
|
||||
const orderedBulk = db.collection('mycollection').initializeOrderedBulkOp();
|
||||
|
||||
orderedBulk.insert({ _id: 1, name: 'John Doe' });
|
||||
orderedBulk.find({ _id: 2 }).updateOne({ $set: { name: 'Jane Doe' } });
|
||||
orderedBulk.find({ _id: 3 }).remove();
|
||||
|
||||
orderedBulk.execute((err, result) => {
|
||||
// Handle error or result
|
||||
});
|
||||
```
|
||||
|
||||
## Example: Unordered Bulk Write
|
||||
|
||||
Here's an example of an unordered bulk write operation:
|
||||
|
||||
```javascript
|
||||
const unorderedBulk = db.collection('mycollection').initializeUnorderedBulkOp();
|
||||
|
||||
unorderedBulk.insert({ _id: 1, name: 'John Doe' });
|
||||
unorderedBulk.find({ _id: 2 }).updateOne({ $set: { name: 'Jane Doe' } });
|
||||
unorderedBulk.find({ _id: 3 }).remove();
|
||||
|
||||
unorderedBulk.execute((err, result) => {
|
||||
// Handle error or result
|
||||
});
|
||||
```
|
||||
|
||||
Remember that using bulk write operations can greatly improve the performance of your MongoDB queries, but make sure to choose the right type (ordered or unordered) based on your application requirements.
|
@@ -1,56 +0,0 @@
|
||||
# Counting Documents
|
||||
|
||||
When working with MongoDB, you might often need to know the number of documents present in a collection. MongoDB provides a few methods to efficiently count documents in a collection. In this section, we will discuss the following methods:
|
||||
|
||||
- `countDocuments()`
|
||||
- `estimatedDocumentCount()`
|
||||
|
||||
## countDocuments()
|
||||
|
||||
The `countDocuments()` method is used to count the number of documents in a collection based on a specified filter. It provides an accurate count that may involve reading all documents in the collection.
|
||||
|
||||
**Syntax:**
|
||||
|
||||
```javascript
|
||||
collection.countDocuments(filter, options);
|
||||
```
|
||||
|
||||
- `filter`: (Optional) A query that will filter the documents before the count is applied.
|
||||
- `options`: (Optional) Additional options for the count operation such as `skip`, `limit`, and `collation`.
|
||||
|
||||
**Example:**
|
||||
|
||||
```javascript
|
||||
db.collection('orders').countDocuments(
|
||||
{ status: 'completed' },
|
||||
(err, count) => {
|
||||
console.log('Number of completed orders: ', count);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
In the example above, we count the number of documents in the `orders` collection that have a`status` field equal to `'completed'`.
|
||||
|
||||
## estimatedDocumentCount()
|
||||
|
||||
The `estimatedDocumentCount()` method provides an approximate count of documents in the collection, without applying any filters. This method uses the collection's metadata to determine the count and is generally faster than `countDocuments()`.
|
||||
|
||||
**Syntax:**
|
||||
|
||||
```javascript
|
||||
collection.estimatedDocumentCount(options);
|
||||
```
|
||||
|
||||
- `options`: (Optional) Additional options for the count operation such as `maxTimeMS`.
|
||||
|
||||
**Example:**
|
||||
|
||||
```javascript
|
||||
db.collection('orders').estimatedDocumentCount((err, count) => {
|
||||
console.log('Estimated number of orders: ', count);
|
||||
});
|
||||
```
|
||||
|
||||
In the example above, we get the estimated number of documents in the `orders` collection.
|
||||
|
||||
Keep in mind that you should use the `countDocuments()` method when you need to apply filters to count documents, while `estimatedDocumentCount()` should be used when an approximate count is sufficient and you don't need to apply any filters.
|
@@ -1,47 +0,0 @@
|
||||
# deleteOne() and others
|
||||
|
||||
When working with MongoDB, you will often need to delete documents or even entire collections to manage and maintain your database effectively. MongoDB provides several methods to remove documents from a collection, allowing for flexibility in how you choose to manage your data. In this section, we will explore key delete methods in MongoDB and provide examples for each.
|
||||
|
||||
## db.collection.deleteOne()
|
||||
|
||||
The `deleteOne()` method is used to delete a single document from a collection. It requires specifying a filter that selects the document(s) to be deleted. If multiple documents match the provided filter, only the first one (by natural order) will be deleted.
|
||||
|
||||
Syntax: `db.collection.deleteOne(FILTER)`
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
db.users.deleteOne({ firstName: 'John' });
|
||||
```
|
||||
|
||||
This command will delete the first `users` document found with a `firstName` field equal to `"John"`.
|
||||
|
||||
## db.collection.deleteMany()
|
||||
|
||||
The `deleteMany()` method is used to remove multiple documents from a collection. Similar to `deleteOne()`, it requires specifying a filter to select the documents to be removed. The difference is that all documents matching the provided filter will be removed.
|
||||
|
||||
Syntax: `db.collection.deleteMany(FILTER)`
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
db.users.deleteMany({ country: 'Australia' });
|
||||
```
|
||||
|
||||
This command will delete all `users` documents with a `country` field equal to `"Australia"`.
|
||||
|
||||
## db.collection.drop()
|
||||
|
||||
In cases where you want to remove an entire collection, including the documents and the metadata, you can use the `drop()` method. This command does not require a filter, as it removes everything in the specified collection.
|
||||
|
||||
Syntax: `db.collection.drop()`
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
db.users.drop();
|
||||
```
|
||||
|
||||
This command would delete the entire `users` collection and all related data.
|
||||
|
||||
It's important to note that these methods will remove the affected documents permanently from the database, so use caution when executing delete commands. Keep in mind to keep backups or use version control to maintain data integrity throughout the lifecycle of your MongoDB database.
|
@@ -1,73 +0,0 @@
|
||||
# find() and relevant
|
||||
|
||||
In MongoDB, the `find()` method is an essential aspect of working with collections. It enables you to search for specific documents within a collection by providing query parameters. In this section, we'll explore various `find` methods and how to filter, sort, and limit the search results.
|
||||
|
||||
## Basic Find Method
|
||||
|
||||
The basic `find()` method is used to fetch all documents within a collection. To use it, you'll simply call the `find()` method on a collection.
|
||||
|
||||
```javascript
|
||||
db.collection_name.find();
|
||||
```
|
||||
|
||||
For example, to fetch all documents from a collection named `users`:
|
||||
|
||||
```javascript
|
||||
db.users.find();
|
||||
```
|
||||
|
||||
## Query Filters
|
||||
|
||||
To search for specific documents, you would need to supply query parameters as a filter within the `find()` method. Filters are passed as JSON objects containing key-value pairs that the documents must match.
|
||||
|
||||
For example, to fetch documents from the `users` collection with the `age` field set to `25`:
|
||||
|
||||
```javascript
|
||||
db.users.find({ age: 25 });
|
||||
```
|
||||
|
||||
## Logical Operators
|
||||
|
||||
MongoDB provides multiple logical operators for more advanced filtering, including `$and`, `$or`, and `$not`. To use logical operators, you pass an array of conditions.
|
||||
|
||||
For example, to find users with an age of `25` and a first name of `John`:
|
||||
|
||||
```javascript
|
||||
db.users.find({ $and: [{ age: 25 }, { first_name: 'John' }] });
|
||||
```
|
||||
|
||||
## Projection
|
||||
|
||||
Projection is used to control which fields are returned in the search results. By specifying a projection, you can choose to include or exclude specific fields in the output.
|
||||
|
||||
To only include the `first_name` and `age` fields of the matching documents:
|
||||
|
||||
```javascript
|
||||
db.users.find({ age: 25 }, { first_name: 1, age: 1 });
|
||||
```
|
||||
|
||||
## Sorting
|
||||
|
||||
You can also sort the results of the `find()` method using the `sort()` function. To sort the results by one or multiple fields, pass a JSON object indicating the order.
|
||||
|
||||
For example, to sort users by their age in ascending order:
|
||||
|
||||
```javascript
|
||||
db.users.find().sort({ age: 1 });
|
||||
```
|
||||
|
||||
## Limit and Skip
|
||||
|
||||
To limit the results of the `find()` method, use the `limit()` function. For instance, to fetch only the first `5` users:
|
||||
|
||||
```javascript
|
||||
db.users.find().limit(5);
|
||||
```
|
||||
|
||||
Additionally, use the `skip()` function to start fetching records after a specific number of rows:
|
||||
|
||||
```javascript
|
||||
db.users.find().skip(10);
|
||||
```
|
||||
|
||||
All these `find` methods combined provide powerful ways to query your MongoDB collections, allowing you to filter, sort, and retrieve the desired documents.
|
@@ -1,65 +0,0 @@
|
||||
# Collections and Methods
|
||||
|
||||
In MongoDB, **collections** are used to organize documents. A collection can be thought of as a container or group used to store documents of similar structure, like a table in relational databases. However, unlike tables, collections don't enforce a strict schema, offering more flexibility in managing your data.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Flexible Schema**: A collection can contain multiple documents with different structures or fields, allowing you to store unstructured or semi-structured data.
|
||||
- **Dynamic**: Collections can be created implicitly or explicitly, and documents can be added or removed easily without affecting others in the collection.
|
||||
|
||||
## Creating Collections
|
||||
|
||||
To create a collection in MongoDB, you can choose from two methods:
|
||||
|
||||
- **Implicit Creation**: When you insert a document without specifying an existing collection, MongoDB automatically creates the collection for you.
|
||||
|
||||
```javascript
|
||||
db.createCollection('users');
|
||||
```
|
||||
|
||||
- **Explicit Creation**: Use the `db.createCollection(name, options)` method to create a collection with specific options:
|
||||
```javascript
|
||||
db.createCollection('users', { capped: true, size: 100000, max: 5000 });
|
||||
```
|
||||
|
||||
## Managing Collections
|
||||
|
||||
- **Insert Documents**: To insert a document into a collection, use the `insertOne()` or `insertMany()` methods.
|
||||
|
||||
```javascript
|
||||
db.users.insertOne({ name: 'John Doe', age: 30, email: 'john@example.com' });
|
||||
|
||||
db.users.insertMany([
|
||||
{ name: 'Jane Doe', age: 28, email: 'jane@example.com' },
|
||||
{ name: 'Mary Jane', age: 32, email: 'mary@example.com' },
|
||||
]);
|
||||
```
|
||||
|
||||
- **Find Documents**: Use the `find()` method to query documents in a collection.
|
||||
|
||||
```javascript
|
||||
db.users.find({ age: { $gt: 30 } });
|
||||
```
|
||||
|
||||
- **Update Documents**: Use the `updateOne()`, `updateMany()`, or `replaceOne()` methods to modify documents in a collection.
|
||||
|
||||
```javascript
|
||||
db.users.updateOne({ name: 'John Doe' }, { $set: { age: 31 } });
|
||||
|
||||
db.users.updateMany({ age: { $gt: 30 } }, { $inc: { age: 1 } });
|
||||
```
|
||||
|
||||
- **Delete Documents**: Use the `deleteOne()` or `deleteMany()` methods to remove documents from a collection.
|
||||
|
||||
```javascript
|
||||
db.users.deleteOne({ name: 'John Doe' });
|
||||
|
||||
db.users.deleteMany({ age: { $lt: 30 } });
|
||||
```
|
||||
|
||||
- **Drop Collection**: To delete the entire collection, use the `drop()` method.
|
||||
```javascript
|
||||
db.users.drop();
|
||||
```
|
||||
|
||||
In summary, collections are an essential part of MongoDB that enable you to efficiently manage and store documents with varying structures. Their flexible schema and dynamic nature make them perfect for handling both unstructured and semi-structured data.
|
@@ -1,74 +0,0 @@
|
||||
# insert() and relevant
|
||||
|
||||
In MongoDB, collections are used to store documents. To add data into these collections, MongoDB provides two primary insertion methods: `insertOne()` and `insertMany()`. In this section, we'll explore the usage and syntax of these methods, along with their options and some basic examples.
|
||||
|
||||
## insertOne()
|
||||
|
||||
The `insertOne()` method is used to insert a single document into a collection. This method returns an `InsertOneResult` object, that shows the outcome of the operation.
|
||||
|
||||
**Syntax:**
|
||||
|
||||
```javascript
|
||||
db.collection.insertOne(
|
||||
<document>,
|
||||
{
|
||||
writeConcern: <document>,
|
||||
ordered: <boolean>,
|
||||
bypassDocumentValidation: <boolean>,
|
||||
comment: <any>
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
**Options:**
|
||||
|
||||
- `writeConcern:` An optional document specifying the level of acknowledgment requested from MongoDB for the write operation.
|
||||
- `ordered:` An optional boolean flag. When set to `true`, MongoDB will return an error if it encounters a duplicate document in the operation. Default is also `true`.
|
||||
- `bypassDocumentValidation:` Optional boolean flag. To validate or not to validate the document against the collection's validation rules. Default is `false`.
|
||||
- `comment:` An optional string or BSON that can be used for descriptive purposes when profiling operations.
|
||||
|
||||
**Example:**
|
||||
|
||||
```javascript
|
||||
db.inventory.insertOne({
|
||||
item: 'book',
|
||||
qty: 1,
|
||||
});
|
||||
```
|
||||
|
||||
## insertMany()
|
||||
|
||||
The `insertMany()` method is used to insert multiple documents into a collection at once. It returns an `InsertManyResult` object, displaying the status of the operation.
|
||||
|
||||
**Syntax:**
|
||||
|
||||
```javascript
|
||||
db.collection.insertMany(
|
||||
[ <document_1>, <document_2>, ... ],
|
||||
{
|
||||
writeConcern: <document>,
|
||||
ordered: <boolean>,
|
||||
bypassDocumentValidation: <boolean>,
|
||||
comment: <any>
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
**Options:**
|
||||
|
||||
- `writeConcern:` Same as mentioned in `insertOne()` method.
|
||||
- `ordered:` Same as mentioned in `insertOne()` method. When set to `true`, MongoDB will insert the documents in the array's order. If a fail occurs, it will stop further processing of the documents. Default is `true`.
|
||||
- `bypassDocumentValidation:` Same as mentioned in `insertOne()` method.
|
||||
- `comment:` Same as mentioned in `insertOne()` method.
|
||||
|
||||
**Example:**
|
||||
|
||||
```javascript
|
||||
db.inventory.insertMany([
|
||||
{ item: 'pen', qty: 5 },
|
||||
{ item: 'pencil', qty: 10 },
|
||||
{ item: 'notebook', qty: 25 },
|
||||
]);
|
||||
```
|
||||
|
||||
In conclusion, insert methods in MongoDB allow users to add documents to a collection with a few simple commands. By understanding the syntax and options available for `insertOne()` and `insertMany()`, we can efficiently store and manage data within MongoDB collections.
|
@@ -1,54 +0,0 @@
|
||||
# update() and relevant
|
||||
|
||||
In MongoDB, update methods are used to modify the existing documents of a collection. They allow you to perform updates on specific fields or the entire document, depending on the query criteria provided. Here is a summary of the most commonly used update methods in MongoDB:
|
||||
|
||||
- **updateOne()**: This method updates the first document that matches the query criteria provided. The syntax for updateOne is:
|
||||
|
||||
```javascript
|
||||
db.collection.updateOne(<filter>, <update>, <options>)
|
||||
```
|
||||
|
||||
- `<filter>`: Specifies the criteria for selecting the document to update.
|
||||
- `<update>`: Specifies the modifications to apply to the selected document.
|
||||
- `<options>`: (Optional) Additional options to configure the behavior of the update operation.
|
||||
|
||||
- **updateMany()**: This method updates multiple documents that match the query criteria provided. The syntax for updateMany is:
|
||||
|
||||
```javascript
|
||||
db.collection.updateMany(<filter>, <update>, <options>)
|
||||
```
|
||||
|
||||
- `<filter>`: Specifies the criteria for selecting the documents to update.
|
||||
- `<update>`: Specifies the modifications to apply to the selected documents.
|
||||
- `<options>`: (Optional) Additional options to configure the behavior of the update operation.
|
||||
|
||||
- **replaceOne()**: This method replaces a document that matches the query criteria with a new document. The syntax for replaceOne is:
|
||||
```javascript
|
||||
db.collection.replaceOne(<filter>, <replacement>, <options>)
|
||||
```
|
||||
- `<filter>`: Specifies the criteria for selecting the document to replace.
|
||||
- `<replacement>`: The new document that will replace the matched document.
|
||||
- `<options>`: (Optional) Additional options to configure the behavior of the replace operation.
|
||||
|
||||
## Update Operators
|
||||
|
||||
MongoDB provides additional update operators to specify the modifications like `$set`, `$unset`, `$inc`, `$push`, `$pull`, and more. Here are a few examples:
|
||||
|
||||
- Use `$set` operator to update the value of a field:
|
||||
|
||||
```javascript
|
||||
db.collection.updateOne({ name: 'John Doe' }, { $set: { age: 30 } });
|
||||
```
|
||||
|
||||
- Use `$inc` operator to increment the value of a field:
|
||||
|
||||
```javascript
|
||||
db.collection.updateMany({ status: 'new' }, { $inc: { views: 1 } });
|
||||
```
|
||||
|
||||
- Use `$push` operator to add an item to an array field:
|
||||
```javascript
|
||||
db.collection.updateOne({ name: 'Jane Doe' }, { $push: { tags: 'mongodb' } });
|
||||
```
|
||||
|
||||
Remember to thoroughly test your update operations to ensure the modifications are done correctly, and always backup your data before making any substantial changes to your documents.
|
@@ -1,55 +0,0 @@
|
||||
# validate()
|
||||
|
||||
The `validate` command is used to examine a MongoDB collection to verify and report on the correctness of its internal structures, such as indexes, namespace details, or documents. This command can also return statistics about the storage and distribution of data within a collection.
|
||||
|
||||
## Usage
|
||||
|
||||
The basic syntax of the `validate` command is as follows:
|
||||
|
||||
```javascript
|
||||
db.runCommand({validate: "<collection_name>", options...})
|
||||
```
|
||||
|
||||
`<collection_name>` is the name of the collection to be validated.
|
||||
|
||||
## Options
|
||||
|
||||
- `full`: (default: false) When set to true, the `validate` command conducts a more thorough inspection of the collection, looking through all its extents, which are contiguous sections of the collection's data on disk. This option should be used with caution as it may impact read and write performance.
|
||||
|
||||
- `background`: (default: false) When set to true, the `validate` command runs in the background, allowing other read and write operations on the collection to proceed concurrently. This option is beneficial for large collections, as it minimizes the impact on system performance.
|
||||
|
||||
## Example
|
||||
|
||||
Validate a collection named "products":
|
||||
|
||||
```javascript
|
||||
db.runCommand({ validate: 'products' });
|
||||
```
|
||||
|
||||
Validate the collection and perform a full check:
|
||||
|
||||
```javascript
|
||||
db.runCommand({ validate: 'products', full: true });
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
The `validate` command returns an object that contains information about the validation process and its results.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"ns": <string>, // Namespace of the validated collection
|
||||
"nIndexes": <number>, // Number of indexes in the collection
|
||||
"keysPerIndex": {
|
||||
<index_name>: <number> // Number of keys per index
|
||||
},
|
||||
"valid": <boolean>, // If true, the collection is valid
|
||||
"errors": [<string>, ...], // Array of error messages, if any
|
||||
"warnings": [<string>, ...], // Array of warning messages, if any
|
||||
"ok": <number> // If 1, the validation command executed successfully
|
||||
}
|
||||
```
|
||||
|
||||
Keep in mind that the `validate` command should be used mainly for diagnostics and troubleshooting purposes, as it can impact system performance when validating large collections or when using the `full` flag. Use it when you suspect that there might be corruption or discrepancies within the collection's data or internal structures.
|
||||
|
||||
That's all about the `validate` command. Now you know how to check the correctness of your MongoDB collections and gather important statistics about their internal structures.
|
@@ -0,0 +1,3 @@
|
||||
# Compound Indexes
|
||||
|
||||
Compound indexes in MongoDB are built on multiple fields in a specified order, optimizing queries that filter on multiple fields. Field order matters significantly as it determines which queries can efficiently use the index. Compound indexes support prefix patterns, meaning they can optimize queries on any left subset of the indexed fields, making them versatile for various query patterns.
|
@@ -0,0 +1,3 @@
|
||||
# Counting Documents
|
||||
|
||||
Counting documents in MongoDB uses methods like countDocuments() for accurate filtered counts and estimatedDocumentCount() for fast approximate totals. countDocuments() supports query filters and provides precise results but may be slower on large collections. estimatedDocumentCount() uses collection metadata for rapid estimates, making it ideal for dashboard metrics and quick statistics.
|
@@ -0,0 +1,3 @@
|
||||
# Creating Indexes
|
||||
|
||||
Creating indexes in MongoDB uses the createIndex() method to build data structures that improve query performance. Indexes can be created on single fields, multiple fields (compound), or with special types like text, geospatial, or hashed. Best practices include analyzing query patterns, creating indexes before large data imports, and monitoring index usage to ensure optimal performance without over-indexing.
|
@@ -0,0 +1,3 @@
|
||||
# Cursors
|
||||
|
||||
Cursors in MongoDB are pointers to query result sets that enable efficient iteration through large datasets without loading all documents into memory. They support methods like hasNext(), next(), forEach(), and limit() for result manipulation. Cursors automatically handle batching, provide lazy loading of results, and can be configured with timeouts and batch sizes for optimal performance.
|
@@ -0,0 +1,3 @@
|
||||
# Data Model & Data Types
|
||||
|
||||
MongoDB uses a flexible document data model storing data in BSON format with rich data types including strings, numbers, dates, arrays, embedded documents, binary data, and ObjectIds. The schema-less design allows varying document structures within collections while maintaining query performance. Documents can contain nested objects and arrays, enabling complex data relationships without traditional table joins.
|
@@ -1,92 +0,0 @@
|
||||
# Array
|
||||
|
||||
In this section, we will discuss the `Array` datatype in MongoDB. Arrays are used to store multiple values in a single field of a MongoDB document. Arrays can contain values of different data types, including strings, numbers, dates, objects, and other embedded arrays.
|
||||
|
||||
## Why use Arrays?
|
||||
|
||||
Arrays are useful when you want to store multiple related items as part of a single document. For example, you might have a list of tags for a blog post or the ingredients for a recipe. Using arrays simplifies querying the data, as you can easily search for documents that contain a specific item in an array or match several items at once.
|
||||
|
||||
## Creating Arrays
|
||||
|
||||
To create an array in MongoDB, simply include it as a field in a document using the square bracket notation (`[]`). You can add values to the array while creating the document or update it later with new items.
|
||||
|
||||
Example of creating an array in a document:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"_id": ObjectId("123xyz"),
|
||||
"name": "John Doe",
|
||||
"hobbies": ["reading", "swimming", "coding"]
|
||||
}
|
||||
```
|
||||
|
||||
## Querying Arrays
|
||||
|
||||
MongoDB provides various operators such as `$in`, `$all`, and `$size`, for querying documents with arrays. The following are some examples:
|
||||
|
||||
- Finding documents with a specific item in an array:
|
||||
|
||||
```javascript
|
||||
db.collection.find({ hobbies: 'swimming' });
|
||||
```
|
||||
|
||||
- Finding documents with any of the specified items in an array:
|
||||
|
||||
```javascript
|
||||
db.collection.find({ hobbies: { $in: ['swimming', 'coding'] } });
|
||||
```
|
||||
|
||||
- Finding documents with all specified items in an array:
|
||||
|
||||
```javascript
|
||||
db.collection.find({ hobbies: { $all: ['reading', 'coding'] } });
|
||||
```
|
||||
|
||||
- Finding documents with a specific array size:
|
||||
|
||||
```javascript
|
||||
db.collection.find({ hobbies: { $size: 3 } });
|
||||
```
|
||||
|
||||
## Updating Arrays
|
||||
|
||||
You can update documents containing arrays by using operators like `$push`, `$addToSet`, `$pull`, and `$pop`.
|
||||
|
||||
- Adding a new item to an array:
|
||||
|
||||
```javascript
|
||||
db.collection.updateOne(
|
||||
{ _id: ObjectId('123xyz') },
|
||||
{ $push: { hobbies: 'painting' } }
|
||||
);
|
||||
```
|
||||
|
||||
- Adding unique items to an array:
|
||||
|
||||
```javascript
|
||||
db.collection.updateOne(
|
||||
{ _id: ObjectId('123xyz') },
|
||||
{ $addToSet: { hobbies: 'painting' } }
|
||||
);
|
||||
```
|
||||
|
||||
- Removing an item from an array:
|
||||
|
||||
```javascript
|
||||
db.collection.updateOne(
|
||||
{ _id: ObjectId('123xyz') },
|
||||
{ $pull: { hobbies: 'reading' } }
|
||||
);
|
||||
```
|
||||
|
||||
- Removing the first or last item from an array:
|
||||
|
||||
```javascript
|
||||
// Remove the first item (use $pop with -1)
|
||||
db.collection.updateOne({ _id: ObjectId('123xyz') }, { $pop: { hobbies: -1 } });
|
||||
|
||||
// Remove the last item (use $pop with 1)
|
||||
db.collection.updateOne({ _id: ObjectId('123xyz') }, { $pop: { hobbies: 1 } });
|
||||
```
|
||||
|
||||
In this section, we've covered the essentials of using the `Array` datatype in MongoDB. With this knowledge, you can efficiently model and query data that requires multiple related items within a single document.
|
@@ -1,50 +0,0 @@
|
||||
# Binary data
|
||||
|
||||
Binary Data is a datatype in MongoDB that is used to store binary content like images, audio files, or any other data that can be represented in binary format. This datatype is particularly useful when you need to store large files, manipulate raw binary data, or work with data that cannot be encoded as UTF-8 strings.
|
||||
|
||||
In MongoDB, binary data is represented using the BSON Binary type, which uses a binary format for encoding and decoding data. The BSON Binary type has several subtypes to better categorize the kind of binary data being stored, such as `B_GENERAL`, `B_FUNCTION`, and `B_BINARY`.
|
||||
|
||||
## Advantages of using Binary Data
|
||||
|
||||
- **Storage:** Storing files directly in the MongoDB database removes the necessity for an additional file storage system and eases the retrieval and management of the files.
|
||||
- **Efficiency:** Binary data can be more efficiently stored and processed than textual representations of the same data.
|
||||
- **Interoperability:** Storing data in binary format allows for seamless communication between systems using different character encodings and serialization formats.
|
||||
|
||||
## Working with Binary Data in MongoDB
|
||||
|
||||
To work with binary data in MongoDB, you will need to utilize the `Binary` class provided by your MongoDB driver. This class offers methods to create, encode, and decode binary data objects.
|
||||
|
||||
Here's an example of creating a binary data object using the `Binary` class in Python:
|
||||
|
||||
```python
|
||||
from bson.binary import Binary
|
||||
from bson import ObjectId
|
||||
|
||||
# Create a binary data object
|
||||
image_data = open("image.jpg", "rb").read()
|
||||
binary_image_data = Binary(image_data)
|
||||
|
||||
# Storing binary data in a MongoDB collection
|
||||
data_collection = db.collection_name
|
||||
document = {
|
||||
"name": "Sample Image",
|
||||
"image_data": binary_image_data,
|
||||
}
|
||||
stored_data = data_collection.insert_one(document)
|
||||
```
|
||||
|
||||
When it comes to retrieving binary data from the database, you can use your MongoDB driver's `find` method to query the required document and access the binary field.
|
||||
|
||||
For example, in Python:
|
||||
|
||||
```python
|
||||
# Retrieve binary data from the database
|
||||
document = data_collection.find_one({"name": "Sample Image"})
|
||||
retrieved_image_data = document["image_data"]
|
||||
|
||||
# Save the retrieved binary data to a new file
|
||||
with open("retrieved_image.jpg", "wb") as f:
|
||||
f.write(retrieved_image_data)
|
||||
```
|
||||
|
||||
Keep in mind that storing large binary files in a MongoDB database might result in performance issues. In such cases, consider using a separate file storage system or MongoDB's [GridFS](https://docs.mongodb.com/manual/core/gridfs/) to store and manage binary data.
|
@@ -1,45 +0,0 @@
|
||||
# Boolean
|
||||
|
||||
The `Boolean` data type in MongoDB is used to store true or false values. Booleans are used when you want to represent a binary state, where a field can have one of two possible values. MongoDB supports the standard `true` and `false` literals for this data type.
|
||||
|
||||
Examples of usage can include representing active/inactive statuses, toggling settings (e.g., sending email notifications), and denoting the presence/absence of a specific feature.
|
||||
|
||||
## Storing Boolean Data
|
||||
|
||||
To store a boolean data value in a MongoDB document, you may use the `true` or `false` literals. Here's an example of a document containing a boolean field named `isActive`:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"name": "John Doe",
|
||||
"isActive": true,
|
||||
"email": "john.doe@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
## Querying Data by Boolean Value
|
||||
|
||||
When you need to query documents based on a boolean value, you can use a query filter that specifies the desired boolean value. For example, if you want to find all active users in the `users` collection:
|
||||
|
||||
```javascript
|
||||
db.users.find({ isActive: true });
|
||||
```
|
||||
|
||||
Similarly, you can retrieve all inactive users with the following query:
|
||||
|
||||
```javascript
|
||||
db.users.find({ isActive: false });
|
||||
```
|
||||
|
||||
## Updating Boolean Data
|
||||
|
||||
Updating or modifying boolean values is as simple as using the `$set` operator with the desired new value. Let's say we want to deactivate a user:
|
||||
|
||||
```javascript
|
||||
db.users.updateOne({ name: 'John Doe' }, { $set: { isActive: false } });
|
||||
```
|
||||
|
||||
This would change the user's `isActive` field value to `false` in the document.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Boolean data types in MongoDB provide a simple and efficient way to represent binary states. Utilize booleans to store true/false values and streamline queries, updates, and other operations to manage data with binary characteristics.
|
@@ -1,28 +0,0 @@
|
||||
# BSON vs JSON
|
||||
|
||||
In MongoDB, data is stored in a binary format called BSON (Binary JSON), which is a superset of JSON (JavaScript Object Notation). While both BSON and JSON are used to represent data in MongoDB, they have some key differences.
|
||||
|
||||
## BSON
|
||||
|
||||
BSON is a binary-encoded serialization of JSON-like documents. It is designed to be efficient in storage, traversability, and encoding/decoding. Some of its key features include:
|
||||
|
||||
- **Binary Encoding**: BSON encodes data in a binary format, which offers better performance and allows the storage of data types not supported by JSON.
|
||||
- **Support for Additional Data Types**: BSON supports more data types compared to JSON, such as `Date`, `Binary`, `ObjectId`, and `Decimal128`. This makes it possible to represent diverse data more accurately in MongoDB documents.
|
||||
- **Efficient Traversability**: In BSON, the size of each element is encoded, which makes it easy to skip over elements, thus making the traversal faster.
|
||||
|
||||
## JSON
|
||||
|
||||
JSON is a lightweight and human-readable data representation format that can be easily parsed and generated by many programming languages. It is used widely as a medium for transmitting data over the web. Some features of JSON include:
|
||||
|
||||
- **Human-readable**: JSON is textual with a simple structure, making it easy for humans to read and write.
|
||||
- **Interoperable**: JSON can be easily parsed and generated by many different programming languages, making it a popular choice for data interchange between applications.
|
||||
- **Limited Data Types**: JSON supports fewer data types compared to BSON, such as strings, numbers, booleans, and `null`. This means that some data, like dates or binary data, must be represented as strings or custom objects in JSON.
|
||||
|
||||
## Summary
|
||||
|
||||
While BSON and JSON are related, they serve different purposes in the context of MongoDB:
|
||||
|
||||
- BSON is the binary format used by MongoDB to store and retrieve data efficiently with support for additional native data types.
|
||||
- JSON, being a more human-readable and widely used format, is typically used for data interchange between MongoDB and applications.
|
||||
|
||||
By using BSON internally, MongoDB can take advantage of its benefits in storage, traversability, and a richer data type representation while still providing the interoperability and readability of JSON through query interfaces and drivers.
|
@@ -1,73 +0,0 @@
|
||||
# Date
|
||||
|
||||
In MongoDB, the _Date_ datatype is used to store the date and time values in a specific format. This is essential when working with date-based data, such as recording timestamps, scheduling events, or organizing data based on time.
|
||||
|
||||
## Date Format
|
||||
|
||||
MongoDB internally stores dates as the number of milliseconds since the Unix epoch (January 1, 1970). This BSON data format makes it efficient for storing and querying date values. However, when working with dates in your application, it is common to use a human-readable format such as ISO 8601.
|
||||
|
||||
## Working with Date
|
||||
|
||||
To create a new Date instance, you can use the JavaScript `Date` object. Here's an example:
|
||||
|
||||
```javascript
|
||||
const currentDate = new Date();
|
||||
```
|
||||
|
||||
When inserting a document with a Date field, you can store the date value as follows:
|
||||
|
||||
```javascript
|
||||
db.events.insertOne({ title: 'Sample Event', eventDate: new Date() });
|
||||
```
|
||||
|
||||
You can also store the current date and time using MongoDB's `$currentDate` operator when updating a document:
|
||||
|
||||
```javascript
|
||||
db.events.updateOne(
|
||||
{ _id: ObjectId('your_document_id') },
|
||||
{
|
||||
$set: {
|
||||
title: 'Sample Event',
|
||||
eventDate: { $currentDate: { $type: 'date' } }
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
## Querying Dates
|
||||
|
||||
To query documents based on date values, you can perform comparisons using various query operators such as `$lt`, `$lte`, `$gt`, `$gte`, and `$eq`. Here are some examples:
|
||||
|
||||
```javascript
|
||||
// Find events that are happening before a certain date
|
||||
const filterDate = new Date('2021-12-31');
|
||||
db.events.find({ eventDate: { $lt: filterDate } });
|
||||
|
||||
// Find events that are happening after a certain date
|
||||
const filterDate = new Date('2022-01-01');
|
||||
db.events.find({ eventDate: { $gt: filterDate } });
|
||||
```
|
||||
|
||||
## Date Aggregations
|
||||
|
||||
MongoDB also provides aggregation functions for working with date values. Some common operations include `$year`, `$month`, `$dayOfMonth`, `$hour`, and `$minute`.
|
||||
|
||||
Example using the `$dayOfYear` and `$year` operators:
|
||||
|
||||
```javascript
|
||||
db.events.aggregate([
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
year: { $year: '$eventDate' },
|
||||
day: { $dayOfYear: '$eventDate' },
|
||||
},
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
This query groups events by the day and year, providing a count of events for each day.
|
||||
|
||||
- [@official@MongoDB Documentation Date](https://www.mongodb.com/docs/manual/reference/method/Date/)
|
@@ -1,37 +0,0 @@
|
||||
# Decimal128
|
||||
|
||||
`Decimal128` is a high-precision 128-bit decimal-based floating-point data type in MongoDB. It provides greater precision and a larger range for storing decimal numbers compared to other common floating-point data types like `Double`.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Precision**: Decimal128 allows for precise storage of decimal numbers with up to 34 decimal points, making it suitable for financial and scientific applications where exact calculations are crucial.
|
||||
- **Range**: Decimal128 supports a wide range of values, ranging from -10^6145 to 10^6145, as well as the smallest non-zero positive and negative numbers around ±10^-6143.
|
||||
- **IEEE 754-2008 compliant**: Decimal128 follows the decimal floating-point arithmetic encoding set by the IEEE 754-2008 international standard, ensuring consistent and accurate results across diverse platforms and systems.
|
||||
|
||||
## Usage
|
||||
|
||||
To specify a `Decimal128` value in MongoDB, use the `$numberDecimal` keyword followed by the decimal value enclosed in quotes. Here's an example demonstrating the insertion of a decimal128 data type:
|
||||
|
||||
```javascript
|
||||
db.example.insertOne({
|
||||
amount: {
|
||||
$numberDecimal: '1234.567890123456789012345678901234',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Alternatively, with the help of the JavaScript BSON library, you can use the `Decimal128.fromString()` function to create a Decimal128 value from a string:
|
||||
|
||||
```javascript
|
||||
const { Decimal128 } = require('bson');
|
||||
|
||||
const decimalValue = Decimal128.fromString(
|
||||
'1234.567890123456789012345678901234'
|
||||
);
|
||||
db.example.insertOne({ amount: decimalValue });
|
||||
```
|
||||
|
||||
## Considerations
|
||||
|
||||
- When querying decimal values, note that MongoDB compares decimal numbers using their mathematical values, rather than their string representation.
|
||||
- Due to the high precision of the `Decimal128` data type, you may encounter rounding differences between MongoDB and other systems or libraries when performing calculations involving mixed data types. To mitigate this, ensure that all operands are converted to the same data type (preferably, `Decimal128`) before performing calculations.
|
@@ -1,37 +0,0 @@
|
||||
# Double
|
||||
|
||||
As a NoSQL database, MongoDB supports a wide range of data types that make it highly versatile for various data storage needs. In this section, we will focus on Double data type.
|
||||
|
||||
## Double
|
||||
|
||||
A Double in MongoDB is a 64-bit floating-point number used to store numerical values that require high precision. This data type is suitable for situations where fractional values or very large numbers are needed (e.g., decimal numbers, scientific calculations, etc.).
|
||||
|
||||
Here's a quick example:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"_id" : ObjectId("5d5c361494341a5f5c529cdc"),
|
||||
"name" : "Pi",
|
||||
"value" : 3.141592653589793
|
||||
}
|
||||
```
|
||||
|
||||
In actual usage, if you try to store a number with a decimal part, MongoDB will save it as a Double. In the example above, the value of Pi is stored as a Double.
|
||||
|
||||
Keep in mind that very large numbers, with or without a decimal part, could also be stored as Double.
|
||||
|
||||
## BSON.Double
|
||||
|
||||
In MongoDB, Double data type is represented as BSON.Double - BSON being the binary serialization format that MongoDB uses to store documents in a binary format (which is also more space-efficient).
|
||||
|
||||
When querying the stored data, you can explicitly cast the value as a Double:
|
||||
|
||||
```javascript
|
||||
db.my_collection.find({ value: { $type: 'double' } });
|
||||
```
|
||||
|
||||
It's important to always remember that although MongoDB provides flexibility in terms of storage, it is crucial to understand the impact of using various data types on performance and storage efficiency.
|
||||
|
||||
That's all you need to know about the Double data type in MongoDB. Now, you can store numerical values with high precision.
|
||||
|
||||
In the next section, we will cover another data type in MongoDB.
|
@@ -1,61 +0,0 @@
|
||||
# Embedded Documents and Arrays
|
||||
|
||||
In MongoDB, one of the powerful features is the ability to store complex data structures like Embedded Documents Arrays. These are essentially arrays of sub-documents (also known as nested documents) that can be stored within a single document. This allows us to model complex data relationships in a highly efficient way while maintaining good performance.
|
||||
|
||||
## What are Embedded Documents Arrays?
|
||||
|
||||
Embedded Documents Arrays are used when you need to represent a 'one-to-many' or hierarchical relationship between data. Instead of using separate collections and references, you can embed the related documents directly into the main document using an array.
|
||||
|
||||
Here's an example of a document containing an embedded array of sub-documents:
|
||||
|
||||
```javascript
|
||||
{
|
||||
_id: 1,
|
||||
name: 'John Doe',
|
||||
addresses: [
|
||||
{
|
||||
street: '123 Main St',
|
||||
city: 'New York',
|
||||
zipcode: '10001'
|
||||
},
|
||||
{
|
||||
street: '456 Broadway',
|
||||
city: 'Los Angeles',
|
||||
zipcode: '90001'
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the `addresses` field represents an array of embedded sub-documents that contain the address details for the user.
|
||||
|
||||
## Advantages
|
||||
|
||||
Embedded Documents Arrays offer a few key advantages:
|
||||
|
||||
- **Read/Write Performance**: Since related data is stored together within the same document, read and write operations can be faster, as they don't require multiple queries or updates.
|
||||
- **Data Consistency**: By storing related data together, you can easily maintain consistency and ensure that related data is always in-sync without having to rely on joins or cross-references.
|
||||
- **Scalability**: Embedded arrays can be nested, allowing you to represent complex data structures while maintaining the benefits of a flexible schema and high performance.
|
||||
|
||||
## When to Use Embedded Documents Arrays
|
||||
|
||||
Consider using Embedded Documents Arrays when:
|
||||
|
||||
- You have a one-to-many relationship
|
||||
- The embedded data does not grow unbounded
|
||||
- The embedded data is strongly related to the parent document
|
||||
- You can benefit from improved read/write performance
|
||||
|
||||
Keep in mind that MongoDB has a document size limitation of 16MB, so if you expect the embedded data to grow over time, you should consider alternative approaches, such as using separate collections and referencing them instead.
|
||||
|
||||
## Querying Embedded Documents Arrays
|
||||
|
||||
Querying documents with embedded arrays is easy thanks to MongoDB's built-in array query operators, such as `$elemMatch`, `$all`, and `$size`. You can also use dot notation to search and update embedded sub-documents.
|
||||
|
||||
For example, to find all users with a specific street address, you would use the following query:
|
||||
|
||||
```javascript
|
||||
db.users.find({ 'addresses.street': '123 Main St' });
|
||||
```
|
||||
|
||||
Overall, Embedded Documents Arrays are a powerful feature in MongoDB, allowing you to store complex data relationships in a performant and efficient manner. Use them wisely to take full advantage of MongoDB's flexibility and scalability.
|
@@ -1,119 +0,0 @@
|
||||
# Data Model and Data Types
|
||||
|
||||
In MongoDB, data is stored in BSON format, which supports various data types. Understanding these data types is essential as they play a crucial role in schema design and query performance. The following is a brief summary of the different data types supported in MongoDB.
|
||||
|
||||
## ObjectId
|
||||
|
||||
`ObjectId` is a 12-byte identifier used as a unique identifier for documents in a collection. It is the default value generated for the `_id` field, ensuring uniqueness within the collection.
|
||||
|
||||
## String
|
||||
|
||||
`String` is used to store text data. It must be a valid UTF-8 encoded string.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"name": "John Doe",
|
||||
}
|
||||
```
|
||||
|
||||
## Boolean
|
||||
|
||||
`Boolean` is used to store true or false values.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"isActive": true,
|
||||
}
|
||||
```
|
||||
|
||||
## Integer
|
||||
|
||||
`Integer` is used to store an integer value. MongoDB supports two integer types: 32-bit (`int`) and 64-bit (`long`).
|
||||
|
||||
```javascript
|
||||
{
|
||||
"age": 28,
|
||||
}
|
||||
```
|
||||
|
||||
## Double
|
||||
|
||||
`Double` is used to store floating-point numbers.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"price": 12.99,
|
||||
}
|
||||
```
|
||||
|
||||
## Date
|
||||
|
||||
`Date` is used to store the date and time in Unix time format (milliseconds timestamp since January 1, 1970, 00:00:00 UTC).
|
||||
|
||||
```javascript
|
||||
{
|
||||
"createdAt": ISODate("2019-02-18T19:29:22.381Z"),
|
||||
}
|
||||
```
|
||||
|
||||
## Array
|
||||
|
||||
`Array` is used to store a list of values in a single field. The values can be of different data types.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"tags": ["mongodb", "database", "noSQL"],
|
||||
}
|
||||
```
|
||||
|
||||
## Object
|
||||
|
||||
`Object` is used to store embedded documents, meaning a document can contain another document.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"address": { "street": "123 Main St", "city": "San Francisco", "state": "CA" },
|
||||
}
|
||||
```
|
||||
|
||||
## Null
|
||||
|
||||
`Null` is used to store a null value, representing the absence of a value or the field.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"middleName": null,
|
||||
}
|
||||
```
|
||||
|
||||
## Binary Data
|
||||
|
||||
`Binary Data` is used to store binary data or byte arrays.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"data": BinData(0, "c3VyZS4="),
|
||||
}
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
`Code` is used to store JavaScript code.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"script": Code("function() { return 'Hello, World!'; }"),
|
||||
}
|
||||
```
|
||||
|
||||
## Regular Expression
|
||||
|
||||
`Regular Expression` is used to store regular expressions.
|
||||
|
||||
```javascript
|
||||
{
|
||||
"pattern": /^mongodb/i,
|
||||
}
|
||||
```
|
||||
|
||||
Understanding and using the appropriate data types while designing your MongoDB schema can significantly improve the performance, storage, and retrieval of your data. Don't forget to consider the specific use cases of your application when choosing data types.
|
@@ -1,37 +0,0 @@
|
||||
# Int32 / Int
|
||||
|
||||
In MongoDB, the `int` (short for integer) data type is used for storing whole numbers without a fractional component. Integers can be either positive or negative and are commonly used in scenarios requiring counting or ranking, such as user's ages, product quantity, or the number of upvotes.
|
||||
|
||||
## Overview
|
||||
|
||||
In MongoDB, integers can be represented in different sizes depending on the range of values required for a specific application. These sizes are as follows:
|
||||
|
||||
- `Int32`: Represents 32-bit integer values between -2^31 and 2^31-1.
|
||||
- `Int64`: Represents 64-bit integer values between -2^63 and 2^63-1.
|
||||
|
||||
By default, MongoDB uses 64-bit integers (`Int64`) when storing integer values for greater flexibility in accommodating various value ranges. However, you can also choose to use 32-bit integers (`Int32`) for smaller value ranges if necessary.
|
||||
|
||||
## Usage
|
||||
|
||||
To store an integer value in a MongoDB document, you can simply include the integer as the value for a field within the document. For example:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"upvotes": 150
|
||||
}
|
||||
```
|
||||
|
||||
Here, `age` and `upvotes` are both integer values representing the age and the number of upvotes of a user.
|
||||
|
||||
If you specifically need to store an integer as a 32-bit or 64-bit value, you can use a driver-specific method or construct BSON objects using the appropriate BSON data type for integers. For example, in the Node.js MongoDB driver, you can use the `Int32` and `Long` constructors from the `mongodb` package:
|
||||
|
||||
```javascript
|
||||
const { Int32, Long } = require('mongodb');
|
||||
|
||||
const myInt32 = new Int32(42); // Creates a 32-bit integer
|
||||
const myInt64 = new Long(9007199254740991); // Creates a 64-bit integer
|
||||
```
|
||||
|
||||
Remember that choosing the appropriate integer size can help optimize storage and performance within your MongoDB application. Use `Int32` for smaller value ranges and `Int64` for larger value ranges as needed.
|
@@ -1,64 +0,0 @@
|
||||
# JavaScript
|
||||
|
||||
In MongoDB, JavaScript is a valuable data type that allows you to store and manipulate code within the database effectively. This data type can be beneficial when working with complex data structures and scenarios that require more flexibility than what the standard BSON types offer. In this section, we will discuss the JavaScript data type, its usage, and some limitations.
|
||||
|
||||
## Usage
|
||||
|
||||
You can store JavaScript directly within MongoDB as a string value, and you can also access JavaScript functions in the context of the `mongo` shell or MongoDB server. To store JavaScript code, you can use the `Code` BSON data type or the `$function` operator, introduced in version 4.4.
|
||||
|
||||
Here's an example of storing JavaScript code in a MongoDB document:
|
||||
|
||||
```javascript
|
||||
db.scripts.insert({
|
||||
name: 'helloWorld',
|
||||
code: new Code("function() { return 'Hello World!'; }"),
|
||||
});
|
||||
```
|
||||
|
||||
And here is an example using the `$function` operator:
|
||||
|
||||
```javascript
|
||||
db.collection.aggregate([
|
||||
{
|
||||
$addFields: {
|
||||
volume: {
|
||||
$function: {
|
||||
body: 'function(l, w, h) { return l * w * h; }',
|
||||
args: ['$length', '$width', '$height'],
|
||||
lang: 'js',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
## Working with JavaScript Functions and Map-Reduce
|
||||
|
||||
You can utilize JavaScript functions with MongoDB's Map-Reduce framework. Map-Reduce is a technique that processes large datasets by applying a map function to each document and then reducing the results according to a reduce function. JavaScript functions can significantly increase the flexibility and expressiveness of these operations.
|
||||
|
||||
An example of Map-Reduce using JavaScript functions:
|
||||
|
||||
```javascript
|
||||
var map = function () {
|
||||
emit(this.category, this.price);
|
||||
};
|
||||
|
||||
var reduce = function (key, values) {
|
||||
return Array.sum(values);
|
||||
};
|
||||
|
||||
db.products.mapReduce(map, reduce, { out: 'total_by_category' });
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
While incredibly flexible, there are some limitations when using JavaScript in MongoDB:
|
||||
|
||||
- **Performance**: JavaScript execution in MongoDB is slower compared to native BSON queries, so it should not be the first choice for high-performance applications.
|
||||
|
||||
- **Concurrency**: JavaScript in MongoDB is single-threaded, which can lead to reduced concurrency and potential blocking if several operations rely on JavaScript code execution.
|
||||
|
||||
- **Security**: Storing and executing JavaScript code may present security risks like code injection attacks. Ensure proper precautions, such as validation and role management, are in place to minimize such risks.
|
||||
|
||||
In conclusion, MongoDB's support for JavaScript as a data type brings flexibility and expressiveness to the database. However, be aware of the performance, concurrency, and security implications when working with JavaScript in your MongoDB applications.
|
@@ -1,41 +0,0 @@
|
||||
# Int64 / Long
|
||||
|
||||
The `Long` data type in MongoDB is a 64-bit integer, which is useful when you need to store large integral values beyond the range of the standard `int` (32-bit integer) data type. The range for the `Long` data type is from `-2^63` to `2^63 - 1`. This data type is suitable for applications that require high-precision numerical data, such as analytics and scientific calculations.
|
||||
|
||||
## Syntax
|
||||
|
||||
To define a field with the `Long` data type in MongoDB, you can use the `$numberLong` keyword. Here's an example of a document with a field named `largeValue` defined as a `Long` data type:
|
||||
|
||||
```json
|
||||
{
|
||||
"largeValue": { "$numberLong": "1234567890123456789" }
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
You can use the `Long` data type to store and query large integral values in your MongoDB collections. To insert a document with a `Long` field, you can use the following syntax:
|
||||
|
||||
```javascript
|
||||
db.collection.insert({
|
||||
largeValue: NumberLong('1234567890123456789'),
|
||||
});
|
||||
```
|
||||
|
||||
To query documents that have a `Long` field with a specific value, you can use the following syntax:
|
||||
|
||||
```javascript
|
||||
db.collection.find({
|
||||
largeValue: NumberLong('1234567890123456789'),
|
||||
});
|
||||
```
|
||||
|
||||
## Considerations
|
||||
|
||||
When using the `Long` data type in MongoDB, keep the following considerations in mind:
|
||||
|
||||
- JavaScript uses the [IEEE 754 floating-point](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) representation for numbers, which may cause a loss of precision when storing and manipulating large integral values. To avoid this, always manipulate `Long` values using MongoDB's built-in `NumberLong()` function, as shown in the examples above.
|
||||
|
||||
- When using the `Long` data type, be aware of the performance trade-offs. Operations on 64-bit integers typically require more processing power and storage space compared to 32-bit integers. If you don't need the extra range provided by the `Long` data type, consider using the `int` data type instead.
|
||||
|
||||
- If you need to store extremely large numbers that exceed the range of the `Long` data type, you may want to consider using the [`Decimal128`](https://docs.mongodb.com/manual/reference/bson-types/#decimal128) data type, which provides 128-bit decimal-based floating-point numbers with 34 decimal digits of precision.
|
@@ -1,38 +0,0 @@
|
||||
# Max Key
|
||||
|
||||
Max Key is a special data type in MongoDB that is used mainly for sorting and comparing values. It has the unique characteristic of being greater than all other BSON types during the sorting process. This makes Max Key quite useful when you need to create a document that should always appear after other documents in a sorted query or when you are setting a limit for a range of data, and you want to ensure that nothing exceeds that limit.
|
||||
|
||||
Here is a brief summary of Max Key:
|
||||
|
||||
## Properties
|
||||
|
||||
- Max Key is a constant that holds the value greater than any other BSON data type value.
|
||||
- It is used for comparing and sorting values in MongoDB collections.
|
||||
- Max Key is a part of the BSON data type, which is the primary data format used in MongoDB for storing, querying, and returning documents.
|
||||
- Max Key is not to be confused with a regular value in a document and is primarily used for internal purposes.
|
||||
|
||||
## Usage
|
||||
|
||||
To use Max Key in your MongoDB implementation, you can insert it into your document using MongoDB syntax as follows:
|
||||
|
||||
```javascript
|
||||
{
|
||||
_id: ObjectId("some_id_value"),
|
||||
field1: "value1",
|
||||
myMaxKeyField: MaxKey()
|
||||
}
|
||||
```
|
||||
|
||||
In this example, `myMaxKeyField` is assigned the Max Key value.
|
||||
|
||||
When you want to sort or compare documents in a collection, Max Key will help ensure that a document will always come last in the results when compared with other BSON types.
|
||||
|
||||
Here is an example of how Max Key can be used in a range query:
|
||||
|
||||
```javascript
|
||||
db.my_collection.find({ age: { $lte: MaxKey() } });
|
||||
```
|
||||
|
||||
This query will return all the documents in `my_collection` where the `age` field is less than or equal to Max Key, essentially retrieving everything, as no value can be greater than Max Key.
|
||||
|
||||
In summary, Max Key plays an essential role in MongoDB by providing a constant value that is always greater than other BSON types, thus ensuring proper sorting and comparing behavior in your implementation.
|
@@ -1,47 +0,0 @@
|
||||
# Min Key
|
||||
|
||||
In this section, we will discuss the "Min Key" data type in MongoDB. It represents the lowest possible BSON value in the sorting order, making it useful when you need to compare values across documents.
|
||||
|
||||
## What is Min Key?
|
||||
|
||||
Min Key is a unique data type in MongoDB that is used to represent the smallest value possible when performing sorting operations. It is often used in queries or schema design when you need to ensure that a specific field has the lowest possible value compared to other BSON types.
|
||||
|
||||
## How to use Min Key
|
||||
|
||||
To use Min Key in MongoDB, you can utilize the `MinKey()` function. Here's an example demonstrating how to insert a document with Min Key data type:
|
||||
|
||||
```javascript
|
||||
// Import the MinKey class from the BSON module
|
||||
const { MinKey } = require('bson');
|
||||
|
||||
// Create an instance of the MinKey class
|
||||
const minValue = new MinKey();
|
||||
|
||||
// Insert a document with a field `priority` having the MinKey value
|
||||
db.myCollection.insertOne({ name: 'example', priority: minValue });
|
||||
```
|
||||
|
||||
This will insert a document with a `priority` field set to the Min Key value.
|
||||
|
||||
## Use cases
|
||||
|
||||
- As a default value on a field when you want to ensure that it will always have the lowest possible value for sorting purposes.
|
||||
|
||||
```javascript
|
||||
// Example schema with a field default set to MinKey
|
||||
const mySchema = new Schema({
|
||||
name: String,
|
||||
priority: { type: Schema.Types.MinKey, default: new MinKey() },
|
||||
});
|
||||
```
|
||||
|
||||
- When you need to find a document with the minimum value for a specific field.
|
||||
|
||||
```javascript
|
||||
// Find the document with the lowest priority
|
||||
db.myCollection.find().sort({ priority: 1 }).limit(1);
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
In this section, we've learned about the "Min Key" data type in MongoDB. We discussed how it is used to represent the smallest value in the BSON data types and its various use cases in sorting and querying the data.
|
@@ -1,34 +0,0 @@
|
||||
# Null
|
||||
|
||||
In MongoDB, the `null` data type represents a missing value or a field that's purposely set to have no value. This is an important data type when you need to represent the absence of a value in a specific field, for example, when a field is optional in your documents.
|
||||
|
||||
## Null in BSON
|
||||
|
||||
MongoDB uses BSON (Binary JSON) as its data model for storage. In BSON, the `null` data type is represented by the type number `0x0A`.
|
||||
|
||||
## Using Null Values in MongoDB
|
||||
|
||||
Here's an example to illustrate how to use the `null` data type in MongoDB:
|
||||
|
||||
```javascript
|
||||
db.users.insertOne({
|
||||
name: 'Alice',
|
||||
email: 'alice@example.com',
|
||||
phone: null,
|
||||
});
|
||||
```
|
||||
|
||||
In this example, we're inserting a new document into the `users` collection with the name, email, and phone fields. For the phone field, instead of leaving it out, we explicitly set it to `null`, making it clear that Alice might have a phone number, but it's currently unknown.
|
||||
|
||||
## Comparison with Null
|
||||
|
||||
When comparing values to `null`, MongoDB will use the following rules:
|
||||
|
||||
- Equality: `null` is equal to `null`.
|
||||
- Inequalities: `null` is considered lower than any other value when it comes to inequalities.
|
||||
|
||||
Keep in mind that there are cases when a field is missing from a document, it might be considered as having a `null` value (depending on the query).
|
||||
|
||||
## Conclusion
|
||||
|
||||
In MongoDB, the `null` data type helps you to represent missing values or fields that shouldn't have a defined value. By setting a field to `null`, you can preserve the structure of your documents and improve the readability of your database design.
|
@@ -1,60 +0,0 @@
|
||||
# ObjectId
|
||||
|
||||
Object ID is a unique identifier in MongoDB and one of its primary datatypes. It is the default identifier created by MongoDB when you insert a document into a collection without specifying an `_id`.
|
||||
|
||||
## Structure of an Object ID
|
||||
|
||||
An Object ID consists of 12 bytes, where:
|
||||
|
||||
- The first 4 bytes represent the timestamp of the document's creation in seconds since the Unix epoch.
|
||||
- The next 3 bytes contain a unique identifier of the machine where the document was created, usually calculated using its hostname.
|
||||
- Following that, 2 bytes represent the process ID of the system where the document was created.
|
||||
- The last 3 bytes are a counter that starts from a random value, incremented for each new document created.
|
||||
|
||||
## Benefits of Object ID
|
||||
|
||||
- The generation of the Object ID is unique, ensuring that no two documents have the same `_id` value in a collection.
|
||||
- The structure of the Object ID provides important information about the document's creation, such as when and where it was created.
|
||||
- The Object ID enables efficient indexing and high performance in large-scale MongoDB deployments.
|
||||
|
||||
## Working with Object ID
|
||||
|
||||
Here are a few examples of how to work with Object IDs in MongoDB:
|
||||
|
||||
**1. Inserting a document without specifying an `_id`:**
|
||||
|
||||
```javascript
|
||||
db.collection.insertOne({ title: 'Example' });
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"_id": ObjectId("60c4237a89293ddc1ef23245"),
|
||||
"title": "Example"
|
||||
}
|
||||
```
|
||||
|
||||
**2. Creating Object ID manually:**
|
||||
|
||||
```javascript
|
||||
const { ObjectId } = require('mongodb');
|
||||
const objectId = new ObjectId();
|
||||
```
|
||||
|
||||
**3. Converting Object ID to a string:**
|
||||
|
||||
```javascript
|
||||
const objectIdStr = objectId.toString();
|
||||
```
|
||||
|
||||
**4. Converting a string back to an Object ID:**
|
||||
|
||||
```javascript
|
||||
const objectIdFromStr = ObjectId(objectIdStr);
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
The Object ID datatype in MongoDB is a very powerful and efficient way to uniquely identify documents in a collection. Its structure provides valuable information about the document's creation, and its design ensures high performance and scalability for large-scale MongoDB deployments. Understanding and effectively utilizing Object IDs is essential for successful MongoDB usage.
|
@@ -1,55 +0,0 @@
|
||||
# Object
|
||||
|
||||
In MongoDB, the Object data type (or BSON data type) is used to represent embedded documents, which are essentially documents inside another document. An object is a key-value pair, where the key is a string and the value can be of any data type supported by MongoDB, including other objects or arrays. This data type is fundamental to MongoDB's flexibility and the schema-less design of the database.
|
||||
|
||||
## Object Structure
|
||||
|
||||
Objects in MongoDB are represented in BSON (Binary JSON) format, which is a binary-encoded version of JSON. BSON helps speed up data processing and supports the use of additional data types not available in standard JSON. BSON documents are hierarchical and can contain other BSON documents, arrays, and other complex data types.
|
||||
|
||||
Here's an example of an object in MongoDB:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"_id": ObjectId("507f191e810c19729de860ea"),
|
||||
"name": "Alice",
|
||||
"age": 28,
|
||||
"address": {
|
||||
"street": "Main Street",
|
||||
"city": "New York",
|
||||
"state": "NY"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the `_id` field contains an ObjectId data type, the `name` and `age` fields contain string and integer data types, respectively, and the `address` field contains a nested object.
|
||||
|
||||
## Querying Objects
|
||||
|
||||
To query objects in MongoDB, you can use dot notation to access nested fields. For example, to find all documents with an address in New York City, you would use the following query:
|
||||
|
||||
```javascript
|
||||
db.collection.find({
|
||||
'address.city': 'New York',
|
||||
});
|
||||
```
|
||||
|
||||
## Updating Objects
|
||||
|
||||
When updating documents with objects, it's important to use appropriate update operators to ensure the correct update behavior. For example, using `$set` to modify specific fields of the object:
|
||||
|
||||
```javascript
|
||||
db.collection.updateOne(
|
||||
{ name: 'Alice' },
|
||||
{ $set: { 'address.city': 'Los Angeles' } }
|
||||
);
|
||||
```
|
||||
|
||||
This operation would only update the `city` field in the `address` object without affecting other fields within the object.
|
||||
|
||||
## Aggregation Operations
|
||||
|
||||
The MongoDB aggregation framework also supports handling objects for various data manipulations. For instance, you can use `$project`, `$group`, or `$unwind` functions to extract data from objects or manipulate object fields as needed.
|
||||
|
||||
Keep in mind that MongoDB encourages denormalized data storage for the sake of query performance, so you should first consider your application requirements and choose a suitable level of normalization or denormalization for your schema design.
|
||||
|
||||
To sum up, the object data type is a versatile aspect of MongoDB's data model, allowing for nesting and structured data storage. Understanding how to work with objects and leverage their functionality is crucial for mastering MongoDB.
|
@@ -1,49 +0,0 @@
|
||||
# Regular Expression
|
||||
|
||||
In MongoDB, regular expressions (regex) are a powerful data type that allows you to search for patterns within text strings. They can be used in query operations to find documents that match a specific pattern and are particularly useful when working with text-based data or when you don't have an exact match for your query.
|
||||
|
||||
## Creating a Regular Expression
|
||||
|
||||
In MongoDB, you can create a regular expression using the `/pattern/flags` syntax or by using the BSON type `RegExp`. Here's an example:
|
||||
|
||||
```javascript
|
||||
// Creating a regex to find documents containing the word 'example'
|
||||
var regex = /example/i; // Using JavaScript regex syntax with 'i' flag (case-insensitive)
|
||||
var bsonRegex = new RegExp('example', 'i'); // Using BSON RegExp type
|
||||
```
|
||||
|
||||
Both methods will result in the same regex pattern, with the `i` flag indicating case-insensitivity.
|
||||
|
||||
## Querying with Regular Expressions
|
||||
|
||||
You can use regular expressions in MongoDB queries using the `$regex` operator or by directly passing the regex pattern:
|
||||
|
||||
```javascript
|
||||
db.collection.find({ field: /example/i }); // Using plain regex pattern
|
||||
db.collection.find({ field: { $regex: /example/i } }); // Using $regex operator
|
||||
```
|
||||
|
||||
## Regular Expression Flags
|
||||
|
||||
MongoDB supports the following regex flags to provide flexibility in pattern matching:
|
||||
|
||||
- `i`: Case-insensitive match
|
||||
- `m`: Multi-line match
|
||||
- `x`: Ignore whitespace and comments in the pattern
|
||||
- `s`: Allow `.` to match all characters, including newlines
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
db.collection.find({ field: { $regex: /example/im } }); // Case-insensitive and multi-line match
|
||||
```
|
||||
|
||||
## Escaping Special Characters
|
||||
|
||||
In regex patterns, certain characters have special meanings, such as `.` (matches any character), `*` (matches zero or more repetitions). To search for a literal character that has a special meaning in regex, you must escape it with a backslash (`\`):
|
||||
|
||||
```javascript
|
||||
db.collection.find({ field: /example\.com/i }); // Search for 'example.com'
|
||||
```
|
||||
|
||||
Regular expressions in MongoDB allow you to search for complex patterns within text strings effectively. By understanding the basic syntax and flags, you can enhance your querying capabilities to find the exact data you need.
|
@@ -1,41 +0,0 @@
|
||||
# String
|
||||
|
||||
A string in MongoDB represents the sequence of characters or text. It's a powerful and flexible data type that can hold anything, from names and descriptions to lengthy texts. Strings in MongoDB are UTF-8 encoded, which makes them compatible with a wide range of characters from many languages.
|
||||
|
||||
Here's a quick overview of strings in MongoDB:
|
||||
|
||||
**Characteristics:**
|
||||
|
||||
- UTF-8 encoded: Supports various characters from multiple languages.
|
||||
- Flexible: Can hold any text, making it suitable for storing different kinds of information.
|
||||
|
||||
**How to use strings in MongoDB:**
|
||||
|
||||
When creating a document in a MongoDB collection, you can simply store the data as a string using key-value pairs. Here's an example:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"name": "John Doe",
|
||||
"city": "New York",
|
||||
"description": "A software developer working at XYZ company.",
|
||||
}
|
||||
```
|
||||
|
||||
In this example, `name`, `city`, and `description` are keys with string values: `"John Doe"`, `"New York"`, and `"A software developer working at XYZ company."`.
|
||||
|
||||
**Queries with strings:**
|
||||
|
||||
You can also perform various queries using strings in MongoDB. Some common query operators used for string manipulation are:
|
||||
|
||||
- `$regex`: Use regular expressions to search for patterns within the string values.
|
||||
- `$text`: Perform a text search on the specified fields in a collection.
|
||||
|
||||
An example of a query with `$regex`:
|
||||
|
||||
```javascript
|
||||
db.collection.find({ name: { $regex: 'J.*' } });
|
||||
```
|
||||
|
||||
This query searches for all documents in the collection with a `name` field starting with the letter `"J"`.
|
||||
|
||||
In summary, strings are an essential data type in MongoDB that can store a wide range of texts and support multiple languages with UTF-8 encoding. They can be used to create flexible documents and perform various queries.
|
@@ -1,21 +0,0 @@
|
||||
# Symbol
|
||||
|
||||
The `Symbol` datatype is a legacy data type in MongoDB. It was primarily used to store textual data with some additional metadata but is now **deprecated** and advised not to be used for new projects.
|
||||
|
||||
The `Symbol` datatype is functionally equivalent to the `String` datatype. The BSON encoding of both Symbol and String is identical, but the Symbol datatype was used to differentiate these two and provide a more powerful and flexible way to extend the MongoDB system for application-specific needs.
|
||||
|
||||
It's also worth mentioning that most MongoDB drivers, including the official driver, do not support the Symbol data type as a separate type. They simply map it to their string representations.
|
||||
|
||||
Although you might encounter Symbols in older databases, it's recommended to use the `String` datatype for new projects or migrate existing symbols to strings, as they don't provide any advantage over the `String` datatype.
|
||||
|
||||
Below is a simple example of how a `Symbol` was stored in MongoDB (note that this is not recommended for new projects):
|
||||
|
||||
```javascript
|
||||
{
|
||||
"_id" : ObjectId("6190e2d973f6e571b47537a0"),
|
||||
"title" : Symbol("Hello World"),
|
||||
"description" : "A simple example of the Symbol datatype"
|
||||
}
|
||||
```
|
||||
|
||||
In conclusion, the `Symbol` datatype is a deprecated legacy datatype in MongoDB that served to store textual data with additional metadata. For new projects, it's highly recommended to use the `String` datatype instead.
|
@@ -1,41 +0,0 @@
|
||||
# Timestamp
|
||||
|
||||
A "Timestamp" in MongoDB is a specific datatype used for tracking the time of an event or a document modification. It's a 64-bit value containing a 4-byte incrementing ordinal for operations within a given second and a 4-byte timestamp representing the seconds since the Unix epoch (Jan 1, 1970).
|
||||
|
||||
## When to use Timestamp
|
||||
|
||||
Timestamps are mainly used for internal MongoDB operations, such as replication and sharding. They can be useful in tracking the order of operations in a distributed system and ensuring data consistency across multiple nodes.
|
||||
|
||||
## Creating and Querying Timestamps
|
||||
|
||||
To create a Timestamp, you can use the BSON Timestamp type. The syntax is as follows:
|
||||
|
||||
```javascript
|
||||
new Timestamp(t, i);
|
||||
```
|
||||
|
||||
Where `t` is the seconds since the Unix epoch, and `i` is an incrementing ordinal for operations within a given second.
|
||||
|
||||
For example, to create a Timestamp for the current time:
|
||||
|
||||
```javascript
|
||||
var currentTimestamp = new Timestamp(
|
||||
Math.floor(new Date().getTime() / 1000),
|
||||
1
|
||||
);
|
||||
```
|
||||
|
||||
To query documents based on their Timestamp, you can use the `$gt`, `$gte`, `$lt`, or `$lte` query operators:
|
||||
|
||||
```javascript
|
||||
// Find all documents with a Timestamp greater than a specified date
|
||||
db.collection.find({
|
||||
timestampFieldName: {
|
||||
$gt: new Timestamp(Math.floor(new Date('2021-01-01').getTime() / 1000), 1),
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Keep in mind that using Timestamps for application purposes is generally not recommended, as their main purpose is to serve internal MongoDB operations. Instead, consider using the `Date` datatype for general-purpose time tracking in your application.
|
||||
|
||||
Overall, Timestamps are a powerful tool in MongoDB for managing operations in distributed systems and maintaining data consistency.
|
@@ -1,26 +0,0 @@
|
||||
# Undefined
|
||||
|
||||
In this section, we will discuss the "undefined" datatype in MongoDB. This datatype was originally used in the early versions of MongoDB, but now it is deprecated and should not be used in new applications.
|
||||
|
||||
## What is 'undefined'?
|
||||
|
||||
An 'undefined' datatype in MongoDB is a data type that signifies that the value of a field has not been set or has been removed. It represents the absence of a value.
|
||||
|
||||
## Why should it not be used?
|
||||
|
||||
In the newer versions of MongoDB, it is recommended to use the `null` value for representing missing or undefined values in the database. Although the `undefined` datatype is still supported for backward compatibility, it is advised to avoid the use of it, as the `null` value is more widely accepted and understood.
|
||||
|
||||
Here is an example to show the difference between `null` and `undefined`:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"field1": null,
|
||||
"field2": undefined
|
||||
}
|
||||
```
|
||||
|
||||
In this example, `field1` has a `null` value, while `field2` has an `undefined` value. However, it is recommended to use `null` instead of `undefined` to maintain better readability and compatibility.
|
||||
|
||||
## Conclusion
|
||||
|
||||
In summary, while the 'undefined' datatype exists in MongoDB, it is now considered deprecated and should be avoided. Instead, it is suggested to use the `null` value to represent fields with missing or undefined values in your database. This will ensure better compatibility and readability of your code when using MongoDB.
|
@@ -0,0 +1,3 @@
|
||||
# Date
|
||||
|
||||
Date data type in MongoDB stores timestamps as 64-bit integers representing milliseconds since Unix epoch (January 1, 1970 UTC). Dates support range queries, sorting, and date arithmetic operations in aggregation pipelines. MongoDB automatically converts JavaScript Date objects and ISO date strings to BSON dates, providing timezone-aware date manipulation and efficient chronological data querying.
|
@@ -0,0 +1,3 @@
|
||||
# Decimal128
|
||||
|
||||
Decimal128 data type in MongoDB provides exact decimal representation for financial and monetary calculations requiring precision. Based on IEEE 754-2008 standard, it supports 34 decimal digits with exact arithmetic operations. Decimal128 eliminates floating-point precision errors, making it essential for applications handling currency, accounting, and scientific computations where decimal accuracy is critical.
|
@@ -0,0 +1,3 @@
|
||||
# delete() and Related Methods
|
||||
|
||||
Delete operations remove documents from MongoDB collections using deleteOne() for single document removal and deleteMany() for multiple documents. These methods use query filters to specify which documents to delete and support write concerns for reliability. Additional methods include findOneAndDelete() for atomic read-and-delete operations and drop() for removing entire collections.
|
@@ -1 +0,0 @@
|
||||
# Backup recovery
|
@@ -1,42 +0,0 @@
|
||||
# mongodump
|
||||
|
||||
**Mongodump** is a utility tool that comes with MongoDB, which is used to create a backup of your data by capturing the BSON output from your MongoDB database. It is especially useful when you want to export data from MongoDB instances, clusters or replica sets for either backup purposes or to migrate data from one environment to another.
|
||||
|
||||
## How it works
|
||||
|
||||
Mongodump connects to a running `mongod` or `mongos` process and extracts the BSON data from the database, which includes collections, their documents, and indexes. The tool stores the exported data in a binary format in a directory named `dump` by default, with each collection's data placed inside a separate BSON file.
|
||||
|
||||
## Usage
|
||||
|
||||
Here's a basic example of using `mongodump`:
|
||||
|
||||
```bash
|
||||
mongodump --uri "mongodb://username:password@host:port/database" --out /path/to/output/dir
|
||||
```
|
||||
|
||||
Replace the values for `username`, `password`, `host`, `port`, and `database` with your actual MongoDB credentials and target database. This command will create a backup of your specified database and will store it in the specified output directory.
|
||||
|
||||
## Options
|
||||
|
||||
Mongodump offers a variety of options to customize your backups:
|
||||
|
||||
- `--uri`: The MongoDB connection string with authentication details.
|
||||
- `--out`: The path to save the output data.
|
||||
- `--db`: The specific database to backup.
|
||||
- `--collection`: The specific collection to backup.
|
||||
- `--query`: An optional query to export only matching documents.
|
||||
- `--oplog`: Include oplog data for a consistent point-in-time snapshot.
|
||||
- `--gzip`: Compress the backup files using gzip.
|
||||
- `--archive`: Write the output to a single archive file instead of individual files.
|
||||
|
||||
## Restoring data with `mongorestore`
|
||||
|
||||
To restore data from a `mongodump` backup, you can use the `mongorestore` tool, which comes with MongoDB as well. Here's a basic example of using `mongorestore`:
|
||||
|
||||
```bash
|
||||
mongorestore --uri "mongodb://username:password@host:port/database" --drop /path/to/backup/dir
|
||||
```
|
||||
|
||||
This command will restore the specified database from the backup directory, and the `--drop` flag will remove any existing data in the target database before restoring the data.
|
||||
|
||||
In summary, `mongodump` is a powerful utility for creating backups of your MongoDB data. Used in conjunction with `mongorestore`, you can easily create, store, and restore data backups as needed.
|
@@ -1,62 +0,0 @@
|
||||
# mongorestore
|
||||
|
||||
`mongorestore` is a utility tool that comes with MongoDB and is used to restore a binary database dump from `mongodump`. It is particularly helpful in scenarios where you need to recover your database, migrate data between MongoDB instances, or manage your data backup strategy.
|
||||
|
||||
## Features
|
||||
|
||||
- Restores BSON data from a `mongodump` output
|
||||
- Supports multiple formats, such as gzip
|
||||
- Allows filtering documents during restore
|
||||
- Can restore data to a new MongoDB instance, or into an existing database and collection
|
||||
|
||||
## Usage
|
||||
|
||||
Here's a basic usage of `mongorestore`:
|
||||
|
||||
```bash
|
||||
mongorestore /path/to/your/dump/folder
|
||||
```
|
||||
|
||||
This command will restore the dump in the specified folder.
|
||||
|
||||
## Common Options
|
||||
|
||||
- `--host`: Specifies the target MongoDB instance (default: `localhost`).
|
||||
- `--port`: Specifies the port number of the target MongoDB instance (default: `27017`).
|
||||
- `--username`: Specifies the username for authentication (if needed).
|
||||
- `--password`: Specifies the password for authentication (if needed).
|
||||
- `--authenticationDatabase`: Specifies the database that holds the user's credentials (default: `admin`).
|
||||
- `--db`: Specifies a single database to restore (default: all databases in the dump folder).
|
||||
- `--collection`: Specifies a single collection to restore (default: all collections in the dump folder).
|
||||
- `--drop`: Drops the database or collection before importing data.
|
||||
- `--gzip`: Decompresses the input BSON files before importing (use with compressed dumps).
|
||||
- `--archive`: Reads/writes the database dump as an archive file.
|
||||
- `--nsExclude`: Exclude namespaces with the specified pattern from the restore.
|
||||
|
||||
## Examples
|
||||
|
||||
Restore only a specific database:
|
||||
|
||||
```bash
|
||||
mongorestore --db=mydatabase /path/to/your/dump/folder
|
||||
```
|
||||
|
||||
Restore using gzip format:
|
||||
|
||||
```bash
|
||||
mongorestore --gzip /path/to/your/compressed/dump/folder
|
||||
```
|
||||
|
||||
Restore with authentication:
|
||||
|
||||
```bash
|
||||
mongorestore --username=myUser --password=myPassword /path/to/your/dump/folder
|
||||
```
|
||||
|
||||
Restore to a remote MongoDB instance:
|
||||
|
||||
```bash
|
||||
mongorestore --host=remoteHost --port=27017 /path/to/your/dump/folder
|
||||
```
|
||||
|
||||
**Important**: Ensure you have proper backups of your data, and test the restore process periodically to validate your backup strategy.
|
@@ -1,50 +0,0 @@
|
||||
# Developer Tools
|
||||
|
||||
In this chapter, we will discuss the various developer tools available for MongoDB. These tools are essential for developers to work efficiently with MongoDB, as they help in areas such as database management, data validation, and data visualization.
|
||||
|
||||
## MongoDB Compass
|
||||
|
||||
[MongoDB Compass](https://www.mongodb.com/products/compass) is a GUI that allows you to visually explore and interact with your data. It provides an intuitive interface for tasks such as creating, reading, updating, and deleting (CRUD) documents, optimizing queries, and managing indexes.
|
||||
|
||||
Key Features:
|
||||
|
||||
- Schema visualization to understand the structure of your data.
|
||||
- Index management for performance optimization.
|
||||
- Aggregation pipeline builder for building complex queries.
|
||||
- Real-time server stats and other metrics.
|
||||
|
||||
## MongoDB Shell
|
||||
|
||||
[The MongoDB Shell](https://www.mongodb.com/products/shell) is an interactive JavaScript interface to MongoDB. It offers an easy way to query and manage your MongoDB databases through a command-line interface.
|
||||
|
||||
Key Features:
|
||||
|
||||
- Create, read, update, and delete documents.
|
||||
- Perform administrative tasks such as data import/export, index creation, and setting up replication.
|
||||
- Write JavaScript functions to automate complex tasks.
|
||||
- Test queries and pipelines before deploying them to your applications.
|
||||
|
||||
## MongoDB Extensions for Visual Studio Code
|
||||
|
||||
[The MongoDB extension for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=mongodb.mongodb-vscode) allows you to work with MongoDB directly from your code editor. This extension enables you to create and execute MongoDB queries, manage connections, and create Playgrounds to prototype queries and manipulate data.
|
||||
|
||||
Key Features:
|
||||
|
||||
- Connect to MongoDB instances (local or remote) with ease.
|
||||
- Run MongoDB commands in the built-in terminal.
|
||||
- Explore databases, collections, and documents.
|
||||
- Create, read, update, and delete documents from within the editor.
|
||||
- Compact and lint your queries for readability and maintainability.
|
||||
|
||||
## MongoDB Drivers
|
||||
|
||||
MongoDB provides [drivers](https://www.mongodb.com/drivers) for various programming languages, allowing developers to create applications that interact with MongoDB databases easily. Officially supported languages include Java, Python, Node.js, C#, and many others.
|
||||
|
||||
Key Features:
|
||||
|
||||
- CRUD operations to manage documents in the database.
|
||||
- Support for advanced queries such as aggregations, text search, and geospatial queries.
|
||||
- Connection pooling for efficient resource utilization.
|
||||
- Tuned for performance and optimized for MongoDB specific features.
|
||||
|
||||
With these developer tools, you can increase your productivity while working with MongoDB and create efficient and maintainable applications. Whether you prefer a visual interface, a command-line environment, or even your favorite coding editor, there is a tool available to make your MongoDB development experience smooth and efficient.
|
@@ -1,36 +0,0 @@
|
||||
# MongoDB Analyzer
|
||||
|
||||
The MongoDB Analyzer for Visual Studio (VS) is a powerful development tool that helps you work with MongoDB by providing an integrated environment within your Visual Studio IDE. This add-on enhances your productivity and efficiency when developing applications with MongoDB, as it offers several benefits such as code assistance, syntax highlighting, IntelliSense support, and more.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Syntax Highlighting**: The MongoDB Analyzer provides syntax highlighting to help you quickly identify and understand different elements in your code, such as variables, operators, and functions.
|
||||
|
||||
- **IntelliSense Support**: IntelliSense is an intelligent code completion feature that predicts and suggests likely entries based on the context. It makes it easier to write queries by providing contextual suggestions based on your input.
|
||||
|
||||
- **Code Snippets**: This feature allows you to insert common MongoDB code patterns and functionalities directly into your code editor with just a few clicks. This can save you time and help maintain a consistent coding style across your project.
|
||||
|
||||
- **Query Profiling**: The MongoDB Analyzer allows you to profile and optimize MongoDB queries. By analyzing query performance, you can identify slow or problematic queries and make appropriate improvements to ensure better performance.
|
||||
|
||||
- **Debugging**: The Analyzer offers debugging support to help you identify and fix issues in your MongoDB queries and scripts, improving the overall reliability of your application.
|
||||
|
||||
- **Integrated Shell**: MongoDB Analyzer offers an integrated shell within Visual Studio that allows you to run MongoDB commands and queries directly within the IDE. This makes it more convenient to interact with your MongoDB instances and perform various tasks without switching between different tools.
|
||||
|
||||
## Getting Started
|
||||
|
||||
To start using MongoDB Analyzer for Visual Studio, follow these steps:
|
||||
|
||||
- Open your Visual Studio IDE and create a new project or open an existing one.
|
||||
|
||||
- Download and install the [MongoDB Analyzer as a NuGet package](https://www.nuget.org/packages/MongoDB.Analyzer/1.0.0) in Visual Studio from:
|
||||
|
||||
- **Package Manager**: Click `Tools` > `NuGet Package Manager` > `Package Manager Console` and then execute this command: ```Install-Package MongoDB.Analyzer -Version 1.0.0```
|
||||
- **.NET CLI**: Click `View` > `Terminal` and then execute this command: ```dotnet add package MongoDB.Analyzer --version 1.0.0```
|
||||
|
||||
- Once installed, it will be added to your project’s Dependencies list, under Analyzers.
|
||||
|
||||
- After installing and once the analyzer has run, you’ll find all of the diagnostic warnings output to the Error List panel. As you start to inspect your code, you’ll also see that any unsupported expressions will be highlighted.
|
||||
|
||||
- Learn more about MongoDB Analyzer from the [official docs](https://www.mongodb.com/developer/languages/csharp/introducing-mongodb-analyzer-dotnet/).
|
||||
|
||||
With the MongoDB Analyzer for Visual Studio, you'll be able to write cleaner, faster, and more efficient code, making it an essential tool for any MongoDB developer.
|
@@ -1,25 +0,0 @@
|
||||
# VS Code Extension
|
||||
|
||||
Visual Studio Code (VS Code) offers an extension for MongoDB that provides a convenient and powerful way to work with MongoDB databases directly from VS Code. This extension allows you to effortlessly manage your MongoDB databases, perform CRUD operations, and visualize your data schema within the VS Code environment. Let's explore the key features of the MongoDB VS Code extension:
|
||||
|
||||
## Features
|
||||
|
||||
- **Explorer Integration**: This extension integrates directly with the VS Code Explorer – allowing you to efficiently browse your databases, collections, and documents sans the need to leave the comfort of your code editor.
|
||||
|
||||
- **Query Execution**: Write and execute MongoDB queries in your editor using the built-in MongoDB Query Playground. Easily execute commands, one by one or in groups, making your data manipulation experience more efficient.
|
||||
|
||||
- **CRUD Operations**: Perform Create, Read, Update, Delete (CRUD) operations on your documents right from the VS Code, without needing to switch between applications, keeping you focused and productive.
|
||||
|
||||
- **Schema Visualization**: Get insights into your data schema by simply hovering over a field or a document. This feature enables you to have a more profound understanding of your data, helping you make better decisions while developing your application.
|
||||
|
||||
- **Snippet Support**: The extension provides template snippets for the most common MongoDB commands, such as find, update or aggregation, to help you write queries faster and adhere to best practices.
|
||||
|
||||
- **Error Monitoring**: Get real-time feedback on syntax or runtime errors while writing MongoDB queries or manipulating documents. This feature helps you identify any potential issues or inconsistencies in your MongoDB operations.
|
||||
|
||||
## Getting Started
|
||||
|
||||
To get started, simply install the [MongoDB for VS Code extension](https://marketplace.visualstudio.com/items?itemName=mongodb.mongodb-vscode) from the Visual Studio Marketplace.
|
||||
|
||||
After installation, you can connect to your MongoDB instance by clicking on the MongoDB icon on the Activity Bar (the vertical bar on the side of the window). From there, you can add your connection string, choose which databases and collections to explore, and interact with your MongoDB data using the extension features described above.
|
||||
|
||||
In conclusion, the MongoDB VS Code extension enhances your productivity as a developer by enabling you to seamlessly work with MongoDB databases directly in your code editor. If you haven't tried it yet, we recommend installing it and exploring its rich set of features.
|
@@ -1,39 +0,0 @@
|
||||
# Developer Tools
|
||||
|
||||
This section explores the essential developer tools you need when working with MongoDB. These developer tools aim to help you manage, interact, and visualize your data to make development tasks quicker and easier.
|
||||
|
||||
## MongoDB Shell (mongo)
|
||||
|
||||
MongoDB Shell, also known as `mongo`, is a command-line interface that allows you to interact with a MongoDB instance. You can use the `mongo` shell to perform CRUD operations, administrative tasks, and manage your databases.
|
||||
|
||||
```bash
|
||||
mongo [options] [db address]
|
||||
```
|
||||
|
||||
## MongoDB Compass
|
||||
|
||||
[MongoDB Compass](https://www.mongodb.com/products/compass) is a graphical user interface (GUI) that simplifies the process of managing your MongoDB data. With Compass, you can visually explore and interact with your data, modify and sort documents, create indexes, and validate data schemas for better data governance.
|
||||
|
||||
## MongoDB Atlas
|
||||
|
||||
[MongoDB Atlas](https://www.mongodb.com/cloud/atlas) is a fully-managed cloud-based database platform offering the best of MongoDB. Its intuitive interface provides an effortless deployment experience, automated backups, self-healing recovery, and many other features that make it an ideal choice for database management.
|
||||
|
||||
## MongoDB APIs and Drivers
|
||||
|
||||
MongoDB offers a variety of APIs and native [drivers](https://docs.mongodb.com/drivers/) for numerous programming languages, enabling developers to build applications using their preferred languages. The most popular of these include:
|
||||
|
||||
- [@article@Node.js Driver](https://docs.mongodb.com/drivers/node/)
|
||||
- [@article@Python Driver (Pymongo)](https://docs.mongodb.com/drivers/pymongo/)
|
||||
- [@article@C# Driver](https://docs.mongodb.com/drivers/csharp/)
|
||||
- [@article@Java Driver](https://docs.mongodb.com/drivers/java/)
|
||||
- [@feed@Explore top posts about Tools](https://app.daily.dev/tags/tools?ref=roadmapsh)
|
||||
|
||||
These drivers provide a high-level API for connecting to MongoDB and performing CRUD operations.
|
||||
|
||||
## Robo 3T / Studio 3T
|
||||
|
||||
[Robo 3T](https://robomongo.org/) (formerly Robomongo) is a lightweight, open-source MongoDB management tool. It provides basic features like connecting to a MongoDB instance, managing databases, collections, and performing CRUD operations.
|
||||
|
||||
[Studio 3T](https://studio3t.com/) is a powerful, feature-rich MongoDB management tool that provides a comprehensive set of tools and features for MongoDB management and development. Studio 3T offers advanced features such as IntelliShell, Query Code, and SQL Migration.
|
||||
|
||||
Choosing the right developer tool depends upon your specific requirements, but being familiar with these tools will offer you a range of options for a faster and more efficient development process.
|
@@ -1,34 +0,0 @@
|
||||
# Language Drivers
|
||||
|
||||
Language drivers are essential tools for developers to interface with MongoDB. They are libraries provided by MongoDB to help developers work with MongoDB in their choice of programming language. With language drivers, you can perform various CRUD operations, manage authentication, and handle connections with the database effectively without worrying about low-level details.
|
||||
|
||||
MongoDB supports a wide range of languages, and some of the most popular drivers are:
|
||||
|
||||
- MongoDB Node.js Driver (`mongodb` for Node.js)
|
||||
- PyMongo (Python)
|
||||
- MongoDB Java Driver (`mongodb-driver-sync` for Java)
|
||||
- MongoDB C#/.NET Driver
|
||||
- MongoDB Go Driver (`mongo-go-driver`)
|
||||
- MongoDB Ruby Driver
|
||||
- MongoDB PHP Library
|
||||
- MongoDB Swift Driver
|
||||
|
||||
With a suitable driver installed, you can interact with MongoDB using the idiomatic style of your programming language. The driver simplifies your code and boosts productivity, as it handles the communication between your application and the MongoDB server.
|
||||
|
||||
To get started with the language driver of your choice, visit the respective documentation linked above. The documentation will help you set up the driver, establish a connection, and perform various database operations in your preferred programming language.
|
||||
|
||||
Remember to always use the latest version of language drivers to ensure compatibility with new MongoDB features and improve overall performance.
|
||||
|
||||
Visit the following resources to learn more:
|
||||
|
||||
- [@official@MongoDB Supported Languages](https://www.mongodb.com/resources/languages)
|
||||
- [@article@C Driver](http://mongoc.org/)
|
||||
- [@opensource@C++ Driver](https://github.com/mongodb/mongo-cxx-driver)
|
||||
- [@article@C# and .NET Driver](https://docs.mongodb.com/drivers/csharp/)
|
||||
- [@article@Go Driver](https://docs.mongodb.com/drivers/go/)
|
||||
- [@article@Java Driver](https://docs.mongodb.com/drivers/java/)
|
||||
- [@article@Node.js Driver](https://docs.mongodb.com/drivers/node/)
|
||||
- [@article@PHP Driver](https://docs.mongodb.com/drivers/php/)
|
||||
- [@article@Python Driver (PyMongo)](https://docs.mongodb.com/drivers/pymongo/)
|
||||
- [@article@Ruby Driver](https://docs.mongodb.com/drivers/ruby/)
|
||||
- [@article@Rust Driver](https://docs.rs/mongodb/1.2.0/mongodb/)
|
@@ -1,25 +0,0 @@
|
||||
# Elastic Search
|
||||
|
||||
Elasticsearch is a powerful open-source search and analytics engine that allows you to store, search, and analyze your data in near real-time. It operates on distributed architecture, making it scalable and highly available for dealing with large volumes of data. Elasticsearch is built on top of Apache Lucene, which provides the foundational search capabilities.
|
||||
|
||||
## Why Elasticsearch?
|
||||
|
||||
Some of the key benefits of Elasticsearch include:
|
||||
|
||||
- **Real-time search:** Elasticsearch indexes data in real-time, allowing you to receive up-to-date search results.
|
||||
- **Scalability:** Elasticsearch can scale horizontally by adding new nodes to the cluster as your data grows.
|
||||
- **Distributed architecture:** The data stored in Elasticsearch is automatically distributed across multiple nodes, providing redundancy and high availability.
|
||||
- **Robust API:** Elasticsearch provides a comprehensive REST API for managing and querying your data.
|
||||
- **Integration with MongoDB**: Elasticsearch can be used in conjunction with MongoDB to provide full-text search capabilities and powerful analytics on MongoDB data.
|
||||
|
||||
## MongoDB Connector for Elasticsearch
|
||||
|
||||
If you're using MongoDB and wish to integrate Elasticsearch for enhanced search and analytics capabilities, you can use the MongoDB Connector for Elasticsearch. This connector is a plugin that enables you to synchronize your MongoDB data with Elasticsearch in real-time, allowing you to take advantage of Elasticsearch's powerful search capabilities on your MongoDB data.
|
||||
|
||||
## Key features:
|
||||
|
||||
- **Real-time synchronization:** The MongoDB Connector for Elasticsearch synchronizes the data in real-time, ensuring that your Elasticsearch cluster is always up-to-date with the latest data from MongoDB.
|
||||
- **Flexible configuration:** You can configure the connector to sync specific fields, collections, and databases, and to apply custom transformations to the data before indexing it in Elasticsearch.
|
||||
- **Resilient:** The connector maintains a checkpoint of the last synced MongoDB operation, so in case of a failure or restart, it can resume the synchronization from the last checkpoint.
|
||||
|
||||
To get started with the MongoDB Connector for Elasticsearch, you can refer to the [official documentation](https://docs.mongodb.com/kafka-connector/current/kafka-elasticsearch-sink/) for installation and configuration instructions.
|
@@ -1,47 +0,0 @@
|
||||
# MongoDB Connectors
|
||||
|
||||
MongoDB Connectors provide the integration between your application and the MongoDB database, allowing your applications to interact with the data stored in MongoDB. These connectors enable you to use your preferred language, framework, or platform to communicate with MongoDB using native APIs or drivers.
|
||||
|
||||
In this section, we'll discuss some commonly used MongoDB Connectors and their main features.
|
||||
|
||||
## MongoDB BI Connector
|
||||
|
||||
The MongoDB BI (Business Intelligence) Connector allows you to connect MongoDB to third-party tools like Tableau or PowerBI, enabling users to create visualizations, reports, and dashboards using data stored in MongoDB. It translates incoming SQL queries into equivalent MongoDB queries, providing a seamless experience when working with your data.
|
||||
|
||||
Key Features:
|
||||
|
||||
- Directly connects to your MongoDB data
|
||||
- Provides integration with popular BI tools
|
||||
- Supports various SQL-compatible clients
|
||||
|
||||
## MongoDB Kafka Connector
|
||||
|
||||
The MongoDB Kafka Connector lets you stream data between Apache Kafka and MongoDB, enabling you to build real-time, event-driven data pipelines that can process and analyze large volumes of data quickly. With this connector, you can use Kafka as the central event bus for your system and automatically persist the events in MongoDB as required.
|
||||
|
||||
Key Features:
|
||||
|
||||
- Support for Kafka Connect API
|
||||
- Flexible and customizable pipelines
|
||||
- Scalable and fault-tolerant design
|
||||
|
||||
## MongoDB Connector for Spark
|
||||
|
||||
The MongoDB Connector for Spark enables you to use MongoDB as a data source or destination for Apache Spark, a powerful analytics engine designed for large-scale data processing. With this connector, you can leverage Spark's advanced capabilities like machine learning and graph processing on your MongoDB data.
|
||||
|
||||
Key Features:
|
||||
|
||||
- Integration with Spark APIs
|
||||
- Support for various Spark libraries like MLlib and GraphX
|
||||
- Parallel data processing for faster analytics
|
||||
|
||||
## MongoDB Language Drivers
|
||||
|
||||
MongoDB provides a range of official and community-supported language drivers that allow developers to interact with MongoDB using their preferred programming language. Officially supported drivers include C, C++, C#, Go, Java, Node.js, PHP, Python, Ruby, Rust, Scala, and Swift. There are also many community-supported drivers for other languages and frameworks.
|
||||
|
||||
Key Features:
|
||||
|
||||
- Native APIs for your preferred language
|
||||
- Connection pooling and efficient use of system resources
|
||||
- Strong consistency and safety with MongoDB's features
|
||||
|
||||
That's an overview of MongoDB Connectors. Remember that each connector has specific setup and configuration steps, so be sure to check the official MongoDB documentation for detailed instructions. Now, you should have a better understanding of how to use MongoDB with your preferred tools and platforms to build powerful applications and perform insightful analysis on your data.
|
@@ -1,35 +0,0 @@
|
||||
# Kafka
|
||||
|
||||
Apache Kafka is a popular open-source distributed streaming platform for building real-time data pipelines and high-throughput applications in a fault-tolerant and scalable manner. This section of our guide will provide you with a summary of the Kafka Connectors related to MongoDB, which helps you to effectively stream data between Kafka and MongoDB.
|
||||
|
||||
## Overview
|
||||
|
||||
Kafka Connect is a powerful framework, part of Apache Kafka, for integrating with external systems like databases, key-value stores, or search indexes through connectors. MongoDB Kafka Connectors allow you to transfer data between the MongoDB Atlas or self-managed MongoDB clusters and Kafka clusters seamlessly.
|
||||
|
||||
## MongoDB Source Connector
|
||||
|
||||
The MongoDB Source Connector streams the data changes (inserts, updates, deletes, and replacements) within the MongoDB cluster into Kafka in real-time. This is particularly useful when you want to process, analyze, or distribute the updates happening within your MongoDB cluster to different Kafka consumers.
|
||||
|
||||
## MongoDB Sink Connector
|
||||
|
||||
The MongoDB Sink Connector enables the transfer of data from a Kafka topic to MongoDB by consuming Kafka records and inserting them into the specified MongoDB collection. This can be used to store the result of stream processing or any other transformations applied to the data coming from Kafka into MongoDB, serving as the final data persistence layer.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Change Data Capture (CDC)**: Kafka Connectors for MongoDB enable change data capture by capturing and streaming database events and changes in real-time.
|
||||
- **Schema Evolution**: Connectors automatically handle schema changes and support using Kafka schema registry to manage schema evolution.
|
||||
- **Ease of setup**: High-level abstraction of the connector framework simplifies setup and configuration.
|
||||
- **Scalability**: Built on top of the Kafka framework, you can scale up to handle massive data streams.
|
||||
|
||||
## Getting Started
|
||||
|
||||
To get started with MongoDB Kafka connectors, you can follow these steps:
|
||||
|
||||
- Download and install [Apache Kafka](https://kafka.apache.org/downloads) and [MongoDB Kafka Connector](https://www.confluent.io/hub/mongodb/kafka-connect-mongodb).
|
||||
- Configure your source/sink connector properties.
|
||||
- Start the Kafka connect runtime with the MongoDB connector.
|
||||
- Verify that your data is being transferred between Kafka and MongoDB as per your requirement.
|
||||
|
||||
For a complete tutorial and detailed configuration options, refer to the [official documentation](https://docs.mongodb.com/kafka-connector/current/kafka-source/).
|
||||
|
||||
In conclusion, MongoDB Kafka Connectors allow you to integrate MongoDB and Kafka seamlessly, enabling real-time data streaming and processing. By using these connectors, you can effectively build scalable, fault-tolerant, and resilient data pipelines between the two technologies.
|
@@ -1,65 +0,0 @@
|
||||
# Spark
|
||||
|
||||
The [Spark Connector](https://docs.mongodb.com/spark-connector/current/) is a powerful integration tool that allows you to use MongoDB as a data source for your Spark applications. This connector provides seamless integration of the robustness and scalability of MongoDB with the computational power of the Apache Spark framework, allowing you to process large volumes of data quickly and efficiently.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **MongoDB as Data Source**: The connector enables loading data from MongoDB into Spark data structures like DataFrames and Datasets.
|
||||
- **Filter Pushdown**: It optimizes performance by pushing down supported filters to execute directly on MongoDB, returning only the relevant data to Spark.
|
||||
- **Aggregation Pipeline**: The connector allows you to execute MongoDB's aggregation pipeline within Spark, for efficient and powerful transformations.
|
||||
|
||||
## Installation
|
||||
|
||||
To start using the Spark Connector for MongoDB, you simply need to add the Maven dependency to your `build.sbt` or `pom.xml` file:
|
||||
|
||||
For SBT:
|
||||
|
||||
```scala
|
||||
libraryDependencies += "org.mongodb.spark" %% "mongo-spark-connector" % "3.0.1"
|
||||
```
|
||||
|
||||
For Maven:
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.mongodb.spark</groupId>
|
||||
<artifactId>mongo-spark-connector_2.12</artifactId>
|
||||
<version>3.0.1</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Here's a basic example of how to work with the MongoDB Spark Connector:
|
||||
|
||||
```scala
|
||||
import org.apache.spark.sql.SparkSession
|
||||
import com.mongodb.spark.MongoSpark
|
||||
|
||||
object MongoDBwithSpark {
|
||||
def main(args: Array[String]): Unit = {
|
||||
val spark = SparkSession.builder()
|
||||
.master("local")
|
||||
.appName("MongoDB Integration")
|
||||
.config("spark.mongodb.input.uri", "mongodb://username:password@host/database.collection")
|
||||
.config("spark.mongodb.output.uri", "mongodb://username:password@host/database.collection")
|
||||
.getOrCreate()
|
||||
|
||||
// Load data from MongoDB into a DataFrame
|
||||
val df = MongoSpark.load(spark)
|
||||
|
||||
// Perform operations on DataFrame
|
||||
// ...
|
||||
|
||||
// Write the DataFrame back to MongoDB
|
||||
MongoSpark.save(df.write.mode("overwrite"))
|
||||
|
||||
// Stop the Spark session
|
||||
spark.stop()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With the MongoDB Spark Connector, you can leverage the power of Apache Spark to analyze and process your data, making it easier to develop analytics solutions and handle complex data processing tasks.
|
||||
|
||||
For more details, check the [official documentation](https://docs.mongodb.com/spark-connector/current/).
|
@@ -0,0 +1,3 @@
|
||||
# Developer Tools
|
||||
|
||||
MongoDB developer tools include MongoDB Compass (GUI), MongoDB Shell (mongosh), VS Code extensions, and various language drivers. These tools provide visual database exploration, query building, performance monitoring, and development assistance. Additional tools include MongoDB Atlas for cloud management, migration utilities, and third-party tools for enhanced productivity and database administration.
|
@@ -0,0 +1,3 @@
|
||||
# Double
|
||||
|
||||
Double data type in MongoDB stores 64-bit floating-point numbers following IEEE 754 standard, providing high precision for decimal calculations. It's the default numeric type for JavaScript numbers and handles both integers and decimals. Doubles support mathematical operations in queries and aggregation pipelines, though precision limitations may occur with very large numbers or repeated calculations requiring exact decimal representation.
|
@@ -0,0 +1 @@
|
||||
# Elastic Search
|
@@ -0,0 +1,3 @@
|
||||
# $elemMatch
|
||||
|
||||
The $elemMatch operator in MongoDB matches documents containing array elements that satisfy multiple specified criteria within a single array element. It ensures all conditions apply to the same array element rather than different elements. $elemMatch is crucial for querying arrays of embedded documents, complex array filtering, and maintaining logical consistency in multi-condition array queries.
|
@@ -0,0 +1,3 @@
|
||||
# Embedded Objects & Arrays
|
||||
|
||||
Embedded objects and arrays in MongoDB enable storing related data within a single document, eliminating the need for separate collections and joins. This design pattern improves query performance and maintains data locality. Embedded structures support nested queries, array operations, and complex data relationships while maintaining document atomicity and enabling efficient retrieval of complete entities.
|
@@ -0,0 +1,3 @@
|
||||
# Encryption at Rest
|
||||
|
||||
Encryption at Rest in MongoDB protects data stored on disk by encrypting database files, indexes, and logs using industry-standard encryption algorithms. This security feature prevents unauthorized access to physical storage media and ensures compliance with data protection regulations. MongoDB supports both enterprise-grade WiredTiger storage engine encryption and file system-level encryption options.
|
@@ -0,0 +1,3 @@
|
||||
# $eq
|
||||
|
||||
The $eq operator in MongoDB matches documents where a field value equals a specified value. It performs exact equality comparison and is the default behavior when using field: value syntax. $eq supports all BSON data types including nested documents and arrays, enabling precise matching in queries. It's fundamental for filtering documents by specific field values in find operations.
|
@@ -0,0 +1 @@
|
||||
# $exclude
|
@@ -0,0 +1,3 @@
|
||||
# $exists
|
||||
|
||||
The $exists operator in MongoDB matches documents based on the presence or absence of a specified field. When set to true, it finds documents containing the field regardless of value (including null), and when false, it finds documents missing the field entirely. $exists is useful for schema validation, data quality checks, and filtering documents with optional fields.
|
@@ -0,0 +1 @@
|
||||
# Expiring
|
@@ -0,0 +1,3 @@
|
||||
# find() and Related Methods
|
||||
|
||||
The find() method retrieves documents from MongoDB collections using query filters, projections, and modifiers. Related methods include findOne() for single documents, findOneAndUpdate() for atomic updates, findOneAndDelete() for atomic deletions, and cursor methods like limit(), skip(), sort() for result manipulation. These methods support complex queries with operators, field projections, and cursor iteration.
|
@@ -0,0 +1,3 @@
|
||||
# Geospatial Indexes
|
||||
|
||||
Geospatial indexes in MongoDB enable efficient querying of geographic coordinate data using 2d, 2dsphere, and geoHaystack index types. They support location-based queries like finding points within a specific distance, polygon intersection, and nearest neighbor searches. These indexes work with GeoJSON objects and legacy coordinate pairs for mapping applications and location services.
|
@@ -0,0 +1,3 @@
|
||||
# $group
|
||||
|
||||
The $group aggregation stage groups documents by specified identifier expressions and applies accumulator operators like $sum, $avg, $max, $min, and $push. It's essential for data aggregation, calculating statistics, and creating summary reports. $group can group by single or multiple fields and supports complex expressions for dynamic grouping criteria.
|
@@ -0,0 +1,3 @@
|
||||
# $gt
|
||||
|
||||
The $gt (greater than) operator in MongoDB selects documents where a field value is greater than a specified value. It works with numbers, dates, strings (lexicographically), and other comparable BSON types. $gt is essential for range queries, date filtering, and numeric comparisons. Combined with other operators, it enables complex filtering conditions for data analysis and reporting.
|
@@ -0,0 +1,3 @@
|
||||
# $gte
|
||||
|
||||
The $gte (greater than or equal to) operator in MongoDB selects documents where a field value is greater than or equal to a specified value. It provides inclusive comparison for range queries, date boundaries, and numeric filtering. $gte is particularly useful for minimum threshold queries, start date filtering, and creating inclusive lower bounds in data selection criteria.
|
@@ -0,0 +1,3 @@
|
||||
# $in
|
||||
|
||||
The $in operator in MongoDB selects documents where a field value matches any value in a specified array. It provides efficient multiple value matching without using multiple $or conditions. $in supports all BSON data types and is particularly useful for filtering by lists of IDs, categories, or enumerated values, offering better performance than equivalent $or queries.
|
@@ -0,0 +1 @@
|
||||
# $include
|
@@ -1 +0,0 @@
|
||||
#
|
@@ -0,0 +1,3 @@
|
||||
# Indexing
|
||||
|
||||
Indexing in MongoDB creates data structures that improve query performance by creating shortcuts to documents. Indexes are built on specific fields and allow the database to quickly locate data without scanning entire collections. MongoDB supports various index types including single field, compound, multikey, geospatial, text, and hashed indexes to optimize different query patterns and use cases.
|
@@ -0,0 +1,3 @@
|
||||
# insert() and Related Methods
|
||||
|
||||
Insert operations add new documents to MongoDB collections using insertOne() for single documents and insertMany() for multiple documents. These methods support options like ordered/unordered inserts, write concerns, and automatic ObjectId generation. MongoDB also provides legacy insert() method and supports upsert operations through update methods when documents don't exist.
|
@@ -0,0 +1,3 @@
|
||||
# Int32
|
||||
|
||||
Int32 data type in MongoDB stores 32-bit signed integers ranging from -2,147,483,648 to 2,147,483,647. This type provides exact integer representation without floating-point precision issues and takes less storage space than doubles. Int32 is ideal for counters, IDs, and whole numbers where precision is critical and the value range fits within 32-bit limits.
|
@@ -0,0 +1,3 @@
|
||||
# Int64 / Long
|
||||
|
||||
Int64 (Long) data type in MongoDB stores 64-bit signed integers with a range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. This type handles large integer values that exceed Int32 limits while maintaining exact precision. Long integers are essential for timestamps, large counters, and applications requiring precise integer arithmetic with very large numbers.
|
@@ -0,0 +1 @@
|
||||
# JavaScript
|
@@ -0,0 +1 @@
|
||||
# Kafka
|
@@ -0,0 +1,3 @@
|
||||
# Kerberos Authentication
|
||||
|
||||
Kerberos authentication in MongoDB provides enterprise-grade security through ticket-based authentication protocol. It integrates with existing Active Directory or Kerberos infrastructures, allowing centralized user management and single sign-on capabilities. This authentication method eliminates password transmission over networks and provides strong mutual authentication between clients and MongoDB servers using encrypted tickets.
|
@@ -0,0 +1 @@
|
||||
# Language Drivers
|
@@ -0,0 +1 @@
|
||||
# LDAP Proxy Auth
|
@@ -0,0 +1,3 @@
|
||||
# $limit
|
||||
|
||||
The $limit aggregation stage restricts the number of documents passed to the next stage in the pipeline. It's commonly used with $sort to get top N results, implement pagination, or reduce data processing overhead. $limit is efficient when combined with indexes and should be placed strategically in the pipeline to minimize document processing in subsequent stages.
|
@@ -0,0 +1,3 @@
|
||||
# $lookup
|
||||
|
||||
The $lookup aggregation stage performs left outer joins between collections, similar to SQL JOINs. It adds an array field containing matching documents from the "joined" collection based on specified local and foreign fields. $lookup supports pipeline-based lookups for complex matching conditions and enables denormalization of related data for efficient querying and reporting.
|
@@ -0,0 +1,3 @@
|
||||
# $lt
|
||||
|
||||
The $lt (less than) operator in MongoDB selects documents where a field value is less than a specified value. It supports comparison operations on numbers, dates, strings, and other ordered BSON types. $lt is commonly used in range queries, date boundaries, and filtering datasets by numeric thresholds. It combines well with $gt to create range-based queries.
|
@@ -0,0 +1,3 @@
|
||||
# $lte
|
||||
|
||||
The $lte (less than or equal to) operator in MongoDB selects documents where a field value is less than or equal to a specified value. It provides inclusive upper bound comparison for range queries, end date filtering, and maximum value constraints. $lte is essential for creating inclusive upper limits in queries and combining with $gte for complete range specifications.
|
@@ -0,0 +1,3 @@
|
||||
# $match
|
||||
|
||||
The $match aggregation stage filters documents in the pipeline, similar to the find() query operation. It should be placed early in the pipeline to reduce document count and improve performance. $match supports all query operators and can use indexes when positioned at the beginning of the pipeline, making it essential for efficient data filtering in aggregation workflows.
|
@@ -0,0 +1 @@
|
||||
# Max Key
|
@@ -0,0 +1 @@
|
||||
# Min Key
|
@@ -1,61 +0,0 @@
|
||||
# $group
|
||||
|
||||
The `$group` operator in MongoDB is used to aggregate and perform operations on the grouped data. The operator allows you to categorize documents in a collection based on specific fields and perform various operations on each group. These operations range from counting the number of documents in a group, to summing up the values of a particular field, to calculating average values, and many more.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
The basic syntax for the `$group` operator is as follows:
|
||||
|
||||
```javascript
|
||||
{
|
||||
$group: {
|
||||
_id: <expression>,
|
||||
<field1>: { <accumulator1> : <expression1> },
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Here's a quick breakdown of the components:
|
||||
|
||||
- `_id`: This field represents the criteria for grouping the documents. It can be a single field name or an expression that returns a value.
|
||||
- `<field1>`: This is the name of the field you want to create in the resulting documents, which store the computed values from the group.
|
||||
- `<accumulator1>`: This is one of the [accumulators](https://docs.mongodb.com/manual/reference/operator/aggregation/#grp._S_grp) that MongoDB provides (e.g. `$sum`, `$avg`, `$min`, `$max`, `$push`, etc.). They specify the operation to perform on the grouped data.
|
||||
- `<expression1>`: This is the field or expression that the `$group` operator applies to the specific accumulator.
|
||||
|
||||
Suppose we have a collection called `orders`, which contains documents representing sales data.
|
||||
|
||||
```javascript
|
||||
[
|
||||
{ _id: 1, customer_id: 'C1', amount: 110 },
|
||||
{ _id: 2, customer_id: 'C2', amount: 150 },
|
||||
{ _id: 3, customer_id: 'C1', amount: 90 },
|
||||
{ _id: 4, customer_id: 'C3', amount: 200 },
|
||||
{ _id: 5, customer_id: 'C2', amount: 50 },
|
||||
];
|
||||
```
|
||||
|
||||
Now, let's group the data by `customer_id` and calculate each customer's total spent amount.
|
||||
|
||||
```javascript
|
||||
db.orders.aggregate([
|
||||
{
|
||||
$group: {
|
||||
_id: '$customer_id',
|
||||
total_spent: { $sum: '$amount' },
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
This query would result in the following:
|
||||
|
||||
```javascript
|
||||
[
|
||||
{ _id: 'C1', total_spent: 200 },
|
||||
{ _id: 'C2', total_spent: 200 },
|
||||
{ _id: 'C3', total_spent: 200 },
|
||||
];
|
||||
```
|
||||
|
||||
Using the `$group` operator, documents in the `orders` collection were grouped by `customer_id`, and the total spent amount for each customer was calculated using the `$sum` accumulator.
|
@@ -1,23 +0,0 @@
|
||||
# $limit
|
||||
|
||||
The $limit operator limits the number of documents passed to the next stage in the pipeline. The $limit operator is useful for debugging and testing pipelines. It is also useful for limiting the number of documents that are returned by a pipeline.
|
||||
|
||||
Here's the syntax for the $limit operator:
|
||||
|
||||
```javascript
|
||||
{ $limit: <number> }
|
||||
```
|
||||
|
||||
Here, `<number>` is the number of documents you want to limit the pipeline to.
|
||||
|
||||
## Example
|
||||
|
||||
Let's say we have a collection named `employees` and we want to limit the number of documents to 5. We can do this using the `$limit` operator:
|
||||
|
||||
```javascript
|
||||
db.employees.aggregate([
|
||||
{
|
||||
$limit: 5,
|
||||
},
|
||||
]);
|
||||
```
|
@@ -1,61 +0,0 @@
|
||||
# $lookup
|
||||
|
||||
The `$lookup` stage in MongoDB is a powerful aggregation pipeline operator that allows you to perform left outer join between two collections. It is used for combining data from multiple collections in a single aggregation pipeline operation.
|
||||
|
||||
Here's a brief summary of `$lookup` operator:
|
||||
|
||||
## Syntax
|
||||
|
||||
The `$lookup` operator uses the following syntax:
|
||||
|
||||
```json
|
||||
{
|
||||
"$lookup": {
|
||||
"from": "<collection_name>",
|
||||
"localField": "<field_from_input_documents>",
|
||||
"foreignField": "<field_from_documents_of_the_from_collection>",
|
||||
"as": "<output_array_field>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
- `from`: The target collection to perform the join operation with.
|
||||
- `localField`: The field from the input collection (i.e., the collection on which the `$lookup` is applied).
|
||||
- `foreignField`: The field from the target collection (i.e., the `from` collection).
|
||||
- `as`: The name of the output array field that will store the joined documents.
|
||||
|
||||
## Example
|
||||
|
||||
Suppose you have two collections, `orders` and `products`. The `orders` collection contains documents with following fields: `orderId`, `productId`, and `quantity`. The `products` collection contains documents with fields: `productId`, `productName`, and `price`.
|
||||
|
||||
To calculate the total amount of each order, you can use the `$lookup` operator along with other aggregation stages:
|
||||
|
||||
```javascript
|
||||
db.orders.aggregate([
|
||||
{
|
||||
$lookup: {
|
||||
from: 'products',
|
||||
localField: 'productId',
|
||||
foreignField: 'productId',
|
||||
as: 'productDetails',
|
||||
},
|
||||
},
|
||||
{
|
||||
$unwind: '$productDetails',
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
orderId: 1,
|
||||
totalAmount: {
|
||||
$multiply: ['$quantity', '$productDetails.price'],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
In this example, `$lookup` will join the `orders` and `products` collections based on `productId`. The joined data will be stored in the new `productDetails` array field. Additional aggregation stages (`$unwind` and `$project`) are used to calculate and display the total amount of each order.
|
||||
|
||||
So, the `$lookup` operator becomes an essential tool when you need to work with data from multiple collections and perform complex data processing tasks in MongoDB.
|
@@ -1,57 +0,0 @@
|
||||
# $match
|
||||
|
||||
The `$match` operator is used to filter documents within the pipeline in the MongoDB aggregation framework. It helps in excluding documents that do not fulfill the specified condition(s). The `$match` operator filters documents and passes only those that match the specified conditions to the next stage of the pipeline.
|
||||
|
||||
The basic syntax for the `$match` operator is as follows:
|
||||
|
||||
```python
|
||||
{ $match: { <query> } }
|
||||
```
|
||||
|
||||
Where `<query>` contains the conditions and the fields which the documents should match.
|
||||
|
||||
### Examples
|
||||
|
||||
Let's take a look at some examples to understand the usage of the `$match` operator.
|
||||
|
||||
Suppose you have a collection named `employees` with the following document structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"_id": ObjectId("123"),
|
||||
"firstName": "John",
|
||||
"lastName": "Doe",
|
||||
"age": 25,
|
||||
"department": "HR"
|
||||
}
|
||||
```
|
||||
|
||||
You are asked to find employees aged above 30. To do this, you can use the `$match` operator as follows:
|
||||
|
||||
```python
|
||||
db.employees.aggregate([
|
||||
{ $match: { age: { $gt: 30 } } }
|
||||
])
|
||||
```
|
||||
|
||||
This returns all employees with age greater than 30.
|
||||
|
||||
**Example 2:**
|
||||
|
||||
Now, let's say you also want to filter employees working in the "HR" department. You can chain conditions to the `$match` operator like this:
|
||||
|
||||
```python
|
||||
db.employees.aggregate([
|
||||
{ $match: { age: { $gt: 30 }, department: "HR" } }
|
||||
])
|
||||
```
|
||||
|
||||
This returns employees who are aged above 30 and working in the "HR" department.
|
||||
|
||||
### Important Things to Keep in Mind
|
||||
|
||||
- When using multiple conditions in the `$match` query, they work as an implicit `$and` operator.
|
||||
- `$match` operator works best earlier in the pipeline. Placing it earlier prevents unnecessary processing and filtering of documents in later stages, which can improve the overall performance of the aggregation pipeline.
|
||||
- The `$match` operator uses most of the standard query operators, like `$gt`, `$lte`, `$in`, and so on.
|
||||
|
||||
In conclusion, the `$match` operator is a powerful and essential tool when working with MongoDB's aggregation pipeline to filter and process datasets based on specific conditions, leading to better performance and more relevant results.
|
@@ -1,80 +0,0 @@
|
||||
# $project
|
||||
|
||||
The `$project` operator helps in selecting or controlling the fields in a document by passing only the necessary attributes to the next stage in the pipeline.
|
||||
|
||||
```javascript
|
||||
db.collection.aggregate([
|
||||
{
|
||||
$project:
|
||||
{
|
||||
field1: <1 or 0>,
|
||||
field2: <1 or 0>,
|
||||
...
|
||||
}
|
||||
}
|
||||
])
|
||||
```
|
||||
|
||||
The value `1` or `0` in the syntax represents whether the field should be included or excluded, respectively.
|
||||
|
||||
Let's assume we have the following documents in a `students` collection:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "_id": 1, "name": "John Doe", "age": 20, "subjects": ["Math", "Physics"] },
|
||||
{
|
||||
"_id": 2,
|
||||
"name": "Jane Smith",
|
||||
"age": 23,
|
||||
"subjects": ["Chemistry", "Biology"]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
We can use the `$project` operator to include only the name and age fields, excluding the subjects:
|
||||
|
||||
```javascript
|
||||
db.students.aggregate([
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
name: 1,
|
||||
age: 1,
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
Returned documents:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "name": "John Doe", "age": 20 },
|
||||
{ "name": "Jane Smith", "age": 23 }
|
||||
]
|
||||
```
|
||||
|
||||
Notice that the resulting documents do not include the "\_id" and "subjects" fields.
|
||||
|
||||
In the example below, we'll exclude the "subjects" field:
|
||||
|
||||
```javascript
|
||||
db.students.aggregate([
|
||||
{
|
||||
$project: {
|
||||
subjects: 0,
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
Returned documents:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "_id": 1, "name": "John Doe", "age": 20 },
|
||||
{ "_id": 2, "name": "Jane Smith", "age": 23 }
|
||||
]
|
||||
```
|
||||
|
||||
Now that you have a basic understanding of the `$project` operator, you can try it out with various scenarios to reshape your MongoDB documents according to your needs. This operator can also be used in conjunction with other operators to perform complex data manipulations within the aggregation pipeline.
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user