diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..30b6c26 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "yaml.schemas": { + "./schema/navigation.schema.json": [ + "*/navigation.{yml,yaml}" + ] + }, + "[yaml]": { + "editor.tabSize": 2, + "editor.insertSpaces": true + } +} \ No newline at end of file diff --git a/api-reference/commands/aggregation/aggregate.md b/api-reference/commands/aggregation/aggregate.md new file mode 100644 index 0000000..0856ead --- /dev/null +++ b/api-reference/commands/aggregation/aggregate.md @@ -0,0 +1,132 @@ +--- +title: Aggregate +description: The aggregate command is used to process data records and return computed results. +type: commands +category: aggregation +--- + +# aggregate + +The `aggregate` command is used to process data records and return computed results. It performs operations on the data, such as filtering, grouping, and sorting, and can transform the data in various ways. The `aggregate` command is highly versatile and is commonly used for data analysis and reporting. + +## Syntax + +```javascript +db.collection.aggregate(pipeline, options) +``` + +- **pipeline**: An array of aggregation stages that process and transform the data. +- **options**: Optional. Specifies more options for the aggregation, such as `explain`, `allowDiskUse`, and `cursor`. + +## Examples + +### Example 1: Calculate total sales by category + +This example demonstrates how to calculate the total sales for each category in the `stores` collection. + +```javascript +db.stores.aggregate([ + { + $unwind: "$sales.salesByCategory" + }, + { + $group: { + _id: "$sales.salesByCategory.categoryName", + totalSales: { $sum: "$sales.salesByCategory.totalSales" } + } + } +]) +``` + +#### Sample output + +```json +[ + { "_id": "Christmas Trees", "totalSales": 3147281 }, + { "_id": "Nuts", "totalSales": 3002332 }, + { "_id": "Camping Tables", "totalSales": 4431667 } +] +``` + +### Example 2: Find stores with full-time staff greater than 10 + +This example shows how to filter stores where the number of full-time staff is greater than 10. + +```javascript +db.stores.aggregate([ + { + $match: { + "staff.totalStaff.fullTime": { $gt: 10 } + } + } +]) +``` + +#### Sample output + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lenore's DJ Equipment Store", + "location": { "lat": -9.9399, "lon": -0.334 }, + "staff": { "totalStaff": { "fullTime": 18, "partTime": 7 } }, + "sales": { + "totalSales": 35911, + "salesByCategory": [ { "categoryName": "DJ Headphones", "totalSales": 35911 } ] + }, + "promotionEvents": [ + { + "discounts": [ + { "categoryName": "DJ Turntables", "discountPercentage": 18 }, + { "categoryName": "DJ Mixers", "discountPercentage": 15 } + ] + } + ], + "tag": [ "#SeasonalSale", "#FreeShipping", "#MembershipDeals" ] + } +] +``` + +### Example 3: List all promotion events with discounts greater than 15% + +This example lists all promotion events where any discount is greater than 15%. + +```javascript +db.stores.aggregate([ + { + $unwind: "$promotionEvents" + }, + { + $unwind: "$promotionEvents.discounts" + }, + { + $match: { + "promotionEvents.discounts.discountPercentage": { $gt: 15 } + } + }, + { + $group: { + _id: "$promotionEvents.eventName", + discounts: { $push: "$promotionEvents.discounts" } + } + } +]) +``` + +#### Sample output + +```json +[ + { + "discounts": [ + { "categoryName": "Basketball Gear", "discountPercentage": 23 }, + { "categoryName": "Wool Carpets", "discountPercentage": 22 }, + { + "categoryName": "Portable Bluetooth Speakers", + "discountPercentage": 24 + } + ] + } +] +``` diff --git a/api-reference/commands/aggregation/count.md b/api-reference/commands/aggregation/count.md new file mode 100644 index 0000000..2c11dc9 --- /dev/null +++ b/api-reference/commands/aggregation/count.md @@ -0,0 +1,81 @@ +--- +title: Count +description: Count command is used to count the number of documents in a collection that match a specified query. +type: commands +category: aggregation +--- + +# count + +The `count` command is used to count the number of documents in a collection that match a specified query. This command is useful for obtaining quick statistics about the data stored in your collections, such as the number of documents that meet certain criteria. + +## Syntax + +The syntax for the `count` command is as follows: + +```javascript +db.collection.count(query, options) +``` + +- `query`: A document specifying the selection criteria using query operators. +- `options`: Optional. A document specifying options, such as `limit` and `skip`. + +## Examples + +Here are some examples to demonstrate the usage of the `count` command: + +### Example 1. Counting all documents in a collection + +To count all documents in the `stores` collection: + +```javascript +db.stores.count({}) +``` + +#### Sample output + +```json +60570 +``` + +### Example 2. Counting documents with specific criteria + +To count the number of stores with a specific `_id` store ID: + +```javascript +db.stores.count({ "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" }) +``` + +#### Sample output + +```json +1 +``` + +### Example 3. Counting documents with nested criteria + +To count the number of stores that have a specific promotion event: + +```javascript +db.stores.count({ "promotionEvents.eventName": "Incredible Discount Days" }) +``` + +#### Sample output + +```json +2156 +``` + +### Example 4. Counting documents with multiple criteria + +To count the number of stores located at a specific latitude and longitude: + +```javascript +db.stores.count({ "location.lat": -2.4111, "location.lon": 72.1041 }) +``` + +#### Sample output + +```json +1 +``` diff --git a/api-reference/commands/aggregation/distinct.md b/api-reference/commands/aggregation/distinct.md new file mode 100644 index 0000000..ea417e0 --- /dev/null +++ b/api-reference/commands/aggregation/distinct.md @@ -0,0 +1,80 @@ +--- +title: Distinct +description: The distinct command is used to find the unique values for a specified field across a single collection. +type: commands +category: aggregation +--- + +# distinct + +The `distinct` command is used to find the unique values for a specified field across a single collection. This command is useful when you need to identify the set of distinct values for a field without retrieving all the documents or when you need to perform operations like filtering or grouping based on unique values. + +## Syntax + +The basic syntax of the `distinct` command is as follows: + +```javascript +db.collection.distinct(field, query, options) +``` + +- `field`: The field that receives the returned distinct values. +- `query`: Optional. A query that specifies the documents from which to retrieve the distinct values. +- `options`: Optional. Other options for the command. + +## Examples + +Here are examples using the provided sample JSON structure. + +### Example 1: Find distinct categories in sales + +To find the distinct `categoryName` in the `salesByCategory` array: + +```javascript +db.stores.distinct("sales.salesByCategory.categoryName") +``` + +#### Sample output + +```json +[ + "Music Theory Books", + "Superfoods", + "Harmonicas", + "Garden Tools" +] +``` + +### Example 2: Find distinct event names in promotion events + +To find the distinct `eventName` in the `promotionEvents` array: + +```javascript +db.stores.distinct("promotionEvents.eventName") +``` + +#### Sample output + +```json +[ + "Super Saver Celebration", + "Incredible Discount Days" +] +``` + +### Example 3: Find distinct discount percentages for a specific event + +To find the distinct `discountPercentage` in the `discounts` array for the "Summer Sale" event: + +```javascript +db.stores.distinct("promotionEvents.discounts.discountPercentage", { "promotionEvents.eventName": "Incredible Discount Days" }) +``` + +#### Sample output + +```json +[ + 6, 17, 22, 25, 9, 15, 14, + 7, 12, 19, 24, 5, 20, 10, + 23, 16, 18, 21, 13, 11, 8 +] +``` diff --git a/api-reference/commands/query-and-write/delete.md b/api-reference/commands/query-and-write/delete.md new file mode 100644 index 0000000..6e258f8 --- /dev/null +++ b/api-reference/commands/query-and-write/delete.md @@ -0,0 +1,176 @@ +--- +title: delete +description: The delete command in DocumentDB deletes documents that match a specified criteria +type: commands +category: query-and-write +--- + +# delete + +The `delete` command is used to remove documents from a collection. A single document or multiple documents can be deleted based on a specified query filter. + +## Syntax + +The basic syntax for the `delete` command is as follows: + +```javascript +db.collection.deleteOne( + , + +) + +db.collection.deleteMany( + , + +) +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **<`filter`>** | A document that specifies the criteria for deletion. Only the documents that match the filter are deleted| +| **`options`** | Optional. A document that specifies options for the delete operation. Common options include writeConcern and collation| + +## Example(s) + +Consider this sample document from the stores collection in the StoreData database. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Delete all documents in a collection + +```javascript +db.stores.deleteMany({}) +``` + +### Example 2 - Delete a document that matches a specified query filter + +```javascript +db.stores.deleteOne({"_id": "68471088-4d45-4164-ae58-a9428d12f310"}) +``` + +### Example 3 - Delete all documents that match a specified query filter + +```javascript +db.stores.deleteMany({"promotionEvents.discounts.discountPercentage": 21}, {"limit": 0}) +``` + +### Example 3 - Delete only one of many documents that match a specified query filter + +```javascript +db.stores.deleteMany({"promotionEvents.discounts.discountPercentage": 21}, {"limit": 1}) +``` + +## Related content + +- [insert with DocumentDB](insert) +- [update with DocumentDB](update) diff --git a/api-reference/commands/query-and-write/find.md b/api-reference/commands/query-and-write/find.md new file mode 100644 index 0000000..c8f3d3f --- /dev/null +++ b/api-reference/commands/query-and-write/find.md @@ -0,0 +1,349 @@ +--- +title: find +description: The find command in DocumentDB returns documents that match a specified filter criteria +type: commands +category: query-and-write +--- + +# find + +The `find` command in DocumentDB is used to query documents within a collection. This command is fundamental for data retrieval operations and can be customized with filters, projections, and query options to fine-tune the results. + +## Syntax + +The basic syntax for the `find` command is: + +```javascript +db.collection.find(query, projection, options) +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **`query`** | A document that specifies the criteria for the documents to be retrieved| +| **`projection`** | (Optional) A document that specifies the fields in the matching documents to be returned in the result set| +| **`options`** | (Optional) A document that specifies options for query behavior and results| + +## Example(s) + +Consider this sample document from the stores collection in the StoreData database. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Retrieve all documents + +The find() command without any query filters returns all documents in the collection. + +```javascript +db.stores.find() +``` + +### Example 2: Retrieve documents with query filters + +Retrieve documents using a filter on the name property. + +```javascript +db.stores.find({"name": "Fourth Coffee | Stationery Haven - New Franco"}) +``` + +### Example 3: Retrieve documents with query filters on objects + +Retrieve documents using query filters on the lat and lon fields within the location object. + +```javascript +db.stores.find({"location.lat": 13.5236, "location.lon": -82.5707}) +``` + +When the dot (.) notation isn't used to reference fields within an object, the query filter should exactly match the entire object including the order of the fields. + +```javascript +db.stores.find({"location": {"lat": 13.5236, "lon": -82.5707}}) +``` + +### Example 4: Retrieve documents with query filters on arrays + +Retrieve documents from the promotionEvents array where the eventName is "Grand Bargain Gala". + +```javascript +db.stores.find({"promotionEvents.eventName": "Grand Bargain Gala"}) +``` + +Retrieve documents from the "discounts" array, which is nested within the promotionEvents array where the categoryName is "Area Rugs". + +```javascript +db.stores.find({"promotionEvents.discounts.categoryName": "Area Rugs"}) +``` + +## Projections + +The second document in the find command specifies the list of fields to project in the response. + +### Include a specific field or multiple fields in the response + +A non-zero integer value or a boolean value of true includes the field in the response. + +```javascript +db.stores.find({"name": "Fourth Coffee | Stationery Haven - New Franco"}, {"location": 1, "sales": 1}) +``` + +```javascript +db.stores.find({"name": "Fourth Coffee | Stationery Haven - New Franco"}, {"location": true, "sales": true}) +``` + +```javascript +db.stores.find({"name": "Fourth Coffee | Stationery Haven - New Franco"}, {"location": 1, "sales": true}) +``` + +```javascript +db.stores.find({"name": "Fourth Coffee | Stationery Haven - New Franco"}, {"location": 1, "sales": -5}) +``` + +All four queries are equivalent and specify the inclusion of the "location" and "sales" fields in the server response. + +```json +{ + "_id": "b5c9f932-4efa-49fd-86ba-b35624d80d95", + "location": { + "lat": 13.5236, + "lon": -82.5707 + }, + "sales": { + "totalSales": 35346, + "salesByCategory": [ + { + "categoryName": "Rulers", + "totalSales": 35346 + } + ] + } +} +``` + +### Exclude a specific field or multiple fields in the response + +An integer value of zero or a boolean value of false excludes the specified field from the query response. + +```javascript +db.stores.find({"name": "Fourth Coffee | Stationery Haven - New Franco"}, {"promotionEvents": 0, "location": 0, "sales": 0}) +``` + +```javascript +db.stores.find({"name": "Fourth Coffee | Stationery Haven - New Franco"}, {"promotionEvents": false, "location": false, "sales": false}) +``` + +Both queries are equivalent and return the following response: + +```json +{ + "_id": "b5c9f932-4efa-49fd-86ba-b35624d80d95", + "name": "Fourth Coffee | Stationery Haven - New Franco", + "staff": { + "totalStaff": { + "fullTime": 17, + "partTime": 5 + } + } +} +``` + +> [!NOTE] +> By default, the _id field is included in the server response. The projection document cannot contain both inclusion and exclusion clauses. However, the _id field is the only exception to this rule and can be excluded along with a list of fields to include and vice versa. + +### Project the first element in an array that matches the query filter criteria + +The "arrayFieldName".$ command projects only the first occurrence of an object in an array that matches the specified query filters. + +```javascript +db.stores.find({"promotionEvents.eventName": "Grand Bargain Gala"}, {"promotionEvents.$": true}) +``` + +One of the documents returned shows only the first element in the promotionEvents array that has the event name "Grand Bargain Gala" while excluding all other elements in the array. + +```json +{ + "_id": "d7fe6fb9-57e8-471a-b8d2-714e3579a415", + "promotionEvents": [ + { + "eventName": "Grand Bargain Gala", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 25 + }, + "endDate": { + "Year": 2024, + "Month": 4, + "Day": 1 + } + }, + "discounts": [ + { + "categoryName": "Area Rugs", + "discountPercentage": 7 + }, + { + "categoryName": "Vinyl Flooring", + "discountPercentage": 12 + } + ] + } + ] +} +``` + +### Project specific elements in an array that match the query filter criteria + +This query projects the eventName property and the nested Year property within the promotionEvents array. + +```javascript +db.stores.find({"promotionEvents.eventName": "Grand Bargain Gala"}, {"promotionEvents.eventName": true, "promotionEvents.promotionalDates.startDate.Year": true}) +``` + +One of the documents returned shows the specified array elements projected in the response. + +```json +{ + "_id": "d7fe6fb9-57e8-471a-b8d2-714e3579a415", + "promotionEvents": [ + { + "eventName": "Grand Bargain Gala", + "promotionalDates": { + "startDate": { + "Year": 2024 + } + } + }, + { + "eventName": "Grand Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024 + } + } + }, + { + "eventName": "Epic Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024 + } + } + } + ] +} +``` + +## Related content + +- [insert with DocumentDB](insert) +- [update with DocumentDB](update) diff --git a/api-reference/commands/query-and-write/findandmodify.md b/api-reference/commands/query-and-write/findandmodify.md new file mode 100644 index 0000000..286c847 --- /dev/null +++ b/api-reference/commands/query-and-write/findandmodify.md @@ -0,0 +1,208 @@ +--- +title: findAndModify +description: The findAndModify command is used to atomically modify and return a single document. +type: commands +category: query-and-write +--- + +# findAndModify + +The `findAndModify` command is used to atomically modify and return a single document. This command is useful for operations that require reading and updating a document in a single step, ensuring data consistency. Common use cases include implementing counters, queues, and other atomic operations. + +## Syntax + +The syntax for the `findAndModify` command is as follows: + +```javascript +db.collection.findAndModify({ + query: , + sort: , + remove: , + update: , + new: , + fields: , + upsert: +}) +``` + +### Parameters + +- **query**: The selection criteria for the document to modify. +- **sort**: Determines which document to modify if the query selects multiple documents. +- **remove**: If `true`, removes the selected document. +- **update**: The modifications to apply. +- **new**: If `true`, returns the modified document rather than the original. +- **fields**: Limits the fields to return for the matching document. +- **upsert**: If `true`, creates a new document if no document matches the query. + +## Examples + +### Example 1: Update total sales + +Suppose we want to update the total sales for the store with `_id` "e5767a9f-cd95-439c-9ec4-7ddc13d22926" to `550000.00` and return the updated document. + +```javascript +db.stores.findAndModify({ + query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" }, + update: { $set: { "sales.totalSales": 550000.00 } }, + new: true +}) +``` + +#### Sample output + +```json +{ + "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926", + "name": "Marina's Eyewear Bargains", + "location": { "lat": -87.4376, "lon": 42.2928 }, + "staff": { "totalStaff": { "fullTime": 20, "partTime": 6 } }, + "sales": { + "totalSales": 550000, + "salesByCategory": [ + { "categoryName": "Round Sunglasses", "totalSales": 39621 }, + { "categoryName": "Reading Glasses", "totalSales": 1146 }, + { "categoryName": "Aviators", "totalSales": 9385 } + ] + }, + "promotionEvents": [ + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 2, "Day": 11 }, + "endDate": { "Year": 2024, "Month": 2, "Day": 18 } + }, + "discounts": [ + { "categoryName": "Square Sunglasses", "discountPercentage": 16 }, + { "categoryName": "Safety Glasses", "discountPercentage": 17 }, + { "categoryName": "Wayfarers", "discountPercentage": 7 }, + { "categoryName": "Eyewear Accessories", "discountPercentage": 12 } + ] + } +], + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 2: Add a new promotional event + +Let's add a new promotional event called "Electronics Super Saver" to the store with `_id_` "e5767a9f-cd95-439c-9ec4-7ddc13d22926" and return the updated document. + +```javascript +db.stores.findAndModify({ + query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" }, + update: { $push: { "promotionEvents": { + "eventName": "Electronics Super Saver", + "promotionalDates": { + "startDate": "2025-09-31", + "endDate": "2025-09-31" + }, + "discounts": [ + { + "categoryName": "Laptops", + "discountPercentage": 45 + }, + { + "categoryName": "Smartphones", + "discountPercentage": 25 + } + ] + }}}, + new: true +}) +``` + +#### Sample output + +```json +{ + "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926", + "name": "Marina's Eyewear Bargains", + "location": { "lat": -87.4376, "lon": 42.2928 }, + "staff": { "totalStaff": { "fullTime": 20, "partTime": 6 } }, + "sales": { + "totalSales": 550000, + "salesByCategory": [ + { "categoryName": "Round Sunglasses", "totalSales": 39621 }, + { "categoryName": "Reading Glasses", "totalSales": 1146 }, + { "categoryName": "Aviators", "totalSales": 9385 } + ] + }, + "promotionEvents": [ + { + "eventName": "Electronics Super Saver", + "promotionalDates": { "startDate": "2025-09-31", "endDate": "2025-09-31" }, + "discounts": [ + { "categoryName": "Laptops", "discountPercentage": 45 }, + { "categoryName": "Smartphones", "discountPercentage": 25 } + ] + } + ], + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 3: Remove a promotional event + +Suppose we want to remove the "Electronics Super Saver" promotional event from the store with `_id` "e5767a9f-cd95-439c-9ec4-7ddc13d22926" and return the original document. + +```javascript +db.stores.findAndModify({ + query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" }, + update: { $pull: { "promotionEvents": { "eventName": "Electronics Super Saver" } } }, + new: true +}) +``` + +#### Sample output + +```json +{ + "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926", + "name": "Marina's Eyewear Bargains", + "location": { "lat": -87.4376, "lon": 42.2928 }, + "staff": { "totalStaff": { "fullTime": 20, "partTime": 6 } }, + "sales": { + "totalSales": 550000, + "salesByCategory": [ + { "categoryName": "Round Sunglasses", "totalSales": 39621 }, + { "categoryName": "Reading Glasses", "totalSales": 1146 }, + { "categoryName": "Aviators", "totalSales": 9385 } + ] + }, + "promotionEvents": [ + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 2, "Day": 11 }, + "endDate": { "Year": 2024, "Month": 2, "Day": 18 } + }, + "discounts": [ + { "categoryName": "Square Sunglasses", "discountPercentage": 16 }, + { "categoryName": "Safety Glasses", "discountPercentage": 17 }, + { "categoryName": "Wayfarers", "discountPercentage": 7 }, + { "categoryName": "Eyewear Accessories", "discountPercentage": 12 } + ] + } + ], + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` diff --git a/api-reference/commands/query-and-write/getMore.md b/api-reference/commands/query-and-write/getMore.md new file mode 100644 index 0000000..a7e3008 --- /dev/null +++ b/api-reference/commands/query-and-write/getMore.md @@ -0,0 +1,51 @@ +--- +title: getMore +description: The getMore command is used to retrieve extra batches of documents from an existing cursor. +type: commands +category: query-and-write +--- + +# getMore + +The `getMore` command is used to retrieve extra batches of documents from an existing cursor. This command is useful when dealing with large datasets that can't be fetched in a single query due to size limitations. The command allows clients to paginate through the results in manageable chunks with commands that return a cursor. For example, [find](./find) and [aggregate](../aggregation/aggregate), to return subsequent batches of documents currently pointed to by the cursor. + +## Syntax + +The syntax for the `getMore` command is as follows: + +```javascript +{ + getMore: , + collection: , + batchSize: +} +``` + +- `getMore`: The unique identifier for the cursor from which to retrieve more documents. +- `collection`: The name of the collection associated with the cursor. +- `batchSize`: (Optional) The number of documents to return in the batch. If not specified, the server uses the default batch size. + +## Examples + +### Example 1: Retrieve more documents from a cursor + +Assume you have a cursor with the ID `1234567890` from the `stores` collection. The following command retrieves the next batch of documents: + +```javascript +{ + getMore: 1234567890, + collection: "stores", + batchSize: 5 +} +``` + +### Example 2: Retrieve more documents without specifying batch size + +If you don't specify the `batchSize`, the server uses the default batch size: + +```javascript +{ + getMore: 1234567890, + collection: "stores" +} +``` diff --git a/api-reference/commands/query-and-write/insert.md b/api-reference/commands/query-and-write/insert.md new file mode 100644 index 0000000..02d409b --- /dev/null +++ b/api-reference/commands/query-and-write/insert.md @@ -0,0 +1,356 @@ +--- +title: insert +description: The insert command in DocumentDB creates new documents in a collection +type: commands +category: query-and-write +--- + +# insert + +The `insert` command is used to create new documents into a collection. Either a single document or multiple documents can be inserted in one go. + +## Syntax + +The basic syntax of the insert command is: + +```javascript +db.collection.insert( + , + { + writeConcern: , + ordered: + } +) +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The document or array of documents to insert into the collection| +| **`writeConcern`** | (Optional) A document expressing the write concern. The write concern describes the level of acknowledgment requested from the server for the write operation| +| **`ordered`** | (Optional) If `true`, the server inserts the documents in the order provided. If `false`, the server can insert the documents in any order and will attempt to insert all documents regardless of errors| + +- ``: The document or array of documents to insert into the collection. +- `writeConcern`: Optional. A document expressing the write concern. The write concern describes the level of acknowledgment requested from the server for the write operation. +- `ordered`: Optional. If `true`, the server inserts the documents in the order provided. If `false`, the server can insert the documents in any order and will attempt to insert all documents regardless of errors. + +## Example(s) + +### Inserting a single document + +The following command inserts a single document into the stores collection in the StoreData database. + +```javascript +db.stores.insertOne({ + "storeId": "12345", + "name": "Boulder Innovations", + "location": { + "lat": 37.7749, + "lon": -122.4194 + }, + "staff": { + "totalStaff": { + "fullTime": 15, + "partTime": 10 + } + }, + "sales": { + "totalSales": 500000.00, + "salesByCategory": [ + { + "categoryName": "Laptops", + "totalSales": 300000.00 + }, + { + "categoryName": "Smartphones", + "totalSales": 200000.00 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Summer Sale", + "promotionalDates": { + "startDate": "2024-06-01", + "endDate": "2024-06-30" + }, + "discounts": [ + { + "categoryName": "Laptops", + "discountPercentage": 15 + }, + { + "categoryName": "Smartphones", + "discountPercentage": 10 + } + ] + }, + { + "eventName": "Holiday Specials", + "promotionalDates": { + "startDate": "2024-12-01", + "endDate": "2024-12-31" + }, + "discounts": [ + { + "categoryName": "Laptops", + "discountPercentage": 20 + }, + { + "categoryName": "Smartphones", + "discountPercentage": 25 + } + ] + } + ] +}) +``` + +### Inserting multiple documents + +The following command inserts an array of documents into the stores collection. + +```javascript +db.stores.insertMany([ + { + "storeId": "12346", + "name": "Graphic Design Institute", + "location": { + "lat": 34.0522, + "lon": -118.2437 + }, + "staff": { + "totalStaff": { + "fullTime": 20, + "partTime": 5 + } + }, + "sales": { + "totalSales": 750000.00, + "salesByCategory": [ + { + "categoryName": "Laptops", + "totalSales": 400000.00 + }, + { + "categoryName": "Smartphones", + "totalSales": 350000.00 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Black Friday", + "promotionalDates": { + "startDate": "2024-11-25", + "endDate": "2024-11-30" + }, + "discounts": [ + { + "categoryName": "Laptops", + "discountPercentage": 25 + }, + { + "categoryName": "Smartphones", + "discountPercentage": 30 + } + ] + } + ] + }, + { + "storeId": "12347", + "name": "Relecloud", + "location": { + "lat": 40.7128, + "lon": -74.0060 + }, + "staff": { + "totalStaff": { + "fullTime": 10, + "partTime": 20 + } + }, + "sales": { + "totalSales": 600000.00, + "salesByCategory": [ + { + "categoryName": "Laptops", + "totalSales": 350000.00 + }, + { + "categoryName": "Smartphones", + "totalSales": 250000.00 + } + ] + }, + "promotionEvents": [ + { + "eventName": "New Year Sale", + "promotionalDates": { + "startDate": "2024-01-01", + "endDate": "2024-01-07" + }, + "discounts": [ + { + "categoryName": "Laptops", + "discountPercentage": 10 + }, + { + "categoryName": "Smartphones", + "discountPercentage": 15 + } + ] + } + ] + } +]) +``` + +### Specifying a value for the _id field + +If the _id field is not specified, the server auto generates a unique ObjectId() value for the document. If the document does specify the _id field, it must be a globally unique value across all documents within the collection. + +If a duplicate value for the _id field is specified, a duplicate key violation error will be thrown by the server. + +```json +{ + "WriteErrors": [ + { + "WriteError": { + "err": { + "index": 0, + "code": 11000, + "errmsg": "Duplicate key violation on the requested collection: Index '_id_'", + "errInfo": "undefined", + "op": { + "testField": "testValue", + "_id": "1" + } + } + } + } + ] +} +``` + +### Inserting multiple documents in order + +Documents that are inserted in bulk can be inserted in order when specifying "ordered": true + +```javascript +db.stores.insertMany([ + { + "_id": "123456", + "storeId": "123456", + "name": "Graphic Design Institute", + "location": { + "lat": 34.0522, + "lon": -118.2437 + }, + "staff": { + "totalStaff": { + "fullTime": 20, + "partTime": 5 + } + }, + "sales": { + "totalSales": 750000.00, + "salesByCategory": [ + { + "categoryName": "Laptops", + "totalSales": 400000.00 + }, + { + "categoryName": "Smartphones", + "totalSales": 350000.00 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Black Friday", + "promotionalDates": { + "startDate": "2024-11-25", + "endDate": "2024-11-30" + }, + "discounts": [ + { + "categoryName": "Laptops", + "discountPercentage": 25 + }, + { + "categoryName": "Smartphones", + "discountPercentage": 30 + } + ] + } + ] + }, + { + "_id": "234567", + "storeId": "234567", + "name": "Relecloud", + "location": { + "lat": 40.7128, + "lon": -74.0060 + }, + "staff": { + "totalStaff": { + "fullTime": 10, + "partTime": 20 + } + }, + "sales": { + "totalSales": 600000.00, + "salesByCategory": [ + { + "categoryName": "Laptops", + "totalSales": 350000.00 + }, + { + "categoryName": "Smartphones", + "totalSales": 250000.00 + } + ] + }, + "promotionEvents": [ + { + "eventName": "New Year Sale", + "promotionalDates": { + "startDate": "2024-01-01", + "endDate": "2024-01-07" + }, + "discounts": [ + { + "categoryName": "Laptops", + "discountPercentage": 10 + }, + { + "categoryName": "Smartphones", + "discountPercentage": 15 + } + ] + } + ] + } +], "ordered": true) +``` + +The ordered insert command returns a response confirming the order in which documents were inserted: + +```json +{ + "acknowledged": true, + "insertedIds": { + "0": "123456", + "1": "234567" + } +} +``` + +## Related content + +- [update with DocumentDB](update) +- [find with DocumentDB](find) diff --git a/api-reference/commands/query-and-write/update.md b/api-reference/commands/query-and-write/update.md new file mode 100644 index 0000000..6ca0e77 --- /dev/null +++ b/api-reference/commands/query-and-write/update.md @@ -0,0 +1,201 @@ +--- +title: update +description: The update commands in DocumentDB modify documents within a collection that match specific filters +type: commands +category: query-and-write +--- + +# update + +The `update` command is used to modify existing documents within a collection. The `update` command can be used to update one or multiple documents based on filtering criteria. Values of fields can be changed, new fields and values can be added and existing fields can be removed. + +## Example(s) + +Consider this sample document from the stores collection in the StoreData database. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Update a single document using the $inc operator + +Increment the totalSales by 10 and decrement the number of full time staff for a document with the specified _id. + +```javascript +db.stores.updateOne({"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4"}, {"$inc": {"sales.salesByCategory.0.totalSales": 10, "staff.totalStaff.fullTime": -6}}) +``` + +### Example 2 - Update a single document using the $min operator + +Update the totalStaff count for the document with the specified _id to 10 if the current value of the field is greater than 10. + +```javascript +db.stores.updateOne({"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4"}, {"$min": {"staff.totalStaff.fullTime": 10}}) +``` + +### Example 3 - Update a single document using the $max operator + +Update the totalStaff count for the document with the specified _id to 14 if the current value of the field is less than 14. + +```javascript +db.stores.updateOne({"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4"}, {"$max": {"staff.totalStaff.fullTime": 14}}) +``` + +### Example 4 - Update a single document using the $mul operator + +Multiple the count of part time employees by 2 for the document with the specified _id value. + +```javascript +db.stores.updateOne({"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4"}, {"$mul": {"staff.totalStaff.partTime": 2}}) +``` + +### Example 5 - Update a single document using the $rename operator + +Rename the totalSales and totalStaff fields to fullSales and staffCounts respectively. + +```javascript +db.stores.updateOne({"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4"}, {"$rename": {"sales.totalSales": "sales.fullSales", "staff.totalStaff": "staff.staffCounts"}}) +``` + +### Example 6 - Update a single document using the $set operator + +Set the fullSales field to 3700 for the document with the specified _id value. + +```javascript +db.stores.updateOne({"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4"}, {"$set": {"sales.fullSales": 3700}}) +``` + +### Example 7 - Update a single document using the $unset operator + +Remove the lon field from the location object in the document with the specified _id value. + +```javascript +db.stores.updateOne({"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4"}, {"$unset": {"location.lon": ""}}) +``` + +### Example 8 - Update multiple documents + +Update all documents where the first promotional event starts in February to start in March. + +```javascript +db.stores.updateMany({"promotionEvents.0.promotionalDates.startDate.Month": 2}, {"$inc": {"promotionEvents.0.promotionalDates.startDate.Month": 1}}) +``` + +### Example 9 - Upsert a single document + +Set the upsert flag to true to create a new document if the document specified in the query filter does not exist in the collection. + +```javascript +db.stores.updateOne({"_id": "NonExistentDocId"}, {"$set": {"name": "Lakeshore Retail", "sales.totalSales": 0}}, {"upsert": true}) +``` + +## Related content + +- [insert with DocumentDB](insert) +- [delete with DocumentDB](delete) diff --git a/api-reference/operators/accumulators/$avg.md b/api-reference/operators/accumulators/$avg.md new file mode 100644 index 0000000..3aee4d5 --- /dev/null +++ b/api-reference/operators/accumulators/$avg.md @@ -0,0 +1,390 @@ +--- +title: $avg +description: The $avg operator computes the average of numeric values for documents in a group, bucket, or window. +type: operators +category: accumulators +--- + +# $avg + +The `$avg` operator computes the average of numeric values across groups of documents or within defined windows. + +## Syntax + +```javascript +$avg: +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Specifies the field or expression to calculate the average. Non-numeric values are ignored. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculate the average sales by category + +To calculate the average sales across all stores within each category, first run a query to group documents within each sales category. Then, calculate the average sales across all documents within each group. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" + }, + { + $group: { + _id: "$sales.salesByCategory.categoryName", + avgSales: { + $avg: "$sales.salesByCategory.totalSales" + } + } + } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "Christmas Trees", + "avgSales": 25987.956989247312 + }, + { + "_id": "Nuts", + "avgSales": 25115.98795180723 + }, + { + "_id": "Camping Tables", + "avgSales": 25012.546153846153 + }, + { + "_id": "Music Theory Books", + "avgSales": 26138.80769230769 + }, + { + "_id": "Fortified Wine", + "avgSales": 24748.672727272726 + }, + { + "_id": "Children's Mystery", + "avgSales": 23764.044444444444 + }, + { + "_id": "Short Throw Projectors", + "avgSales": 27157.472222222223 + }, + { + "_id": "Pliers", + "avgSales": 26712.875 + }, + { + "_id": "Bluetooth Headphones", + "avgSales": 26311.58653846154 + }, + { + "_id": "Video Storage", + "avgSales": 26121.475 + }, + { + "_id": "Cleansers", + "avgSales": 25836.397058823528 + }, + { + "_id": "Camera Straps", + "avgSales": 22487.609375 + }, + { + "_id": "Carry-On Bags", + "avgSales": 24294.263157894737 + }, + { + "_id": "Disinfectant Wipes", + "avgSales": 27066.929411764704 + }, + { + "_id": "Insignia Smart TVs", + "avgSales": 27096.83950617284 + }, + { + "_id": "Toner Refill Kits", + "avgSales": 24963.71052631579 + }, + { + "_id": "iPads", + "avgSales": 22583.882352941175 + }, + { + "_id": "Memory Foam Mattresses", + "avgSales": 28073.05172413793 + }, + { + "_id": "Storage Baskets", + "avgSales": 24092.514705882353 + }, + { + "_id": "Body Spray", + "avgSales": 26080.84375 + } +] +``` + +### Example 2: Using `$avg` in `$bucket` + +To get the averages sales within specific sales boundaries, this query creates buckets based on sales values and calculates the avg sales within each bucket. + +```javascript +db.stores.aggregate([{ + $bucket: { + groupBy: "$sales.totalSales", + boundaries: [0, 1000, 5000, 10000], + default: "Other", + output: { + avgSales: { + $avg: "$sales.totalSales" + } + } + } +}]) +``` + +This query returns the following results: + +```json +[ + { + "_id": 1000, + "avgSales": 3029.053674121406 + }, + { + "_id": "Other", + "avgSales": 52169.85442987472 + }, + { + "_id": 0, + "avgSales": 576.3164179104477 + }, + { + "_id": 5000, + "avgSales": 7538.786819770345 + } +] +``` + +### Example 3: Using `$avg` in `$setWindowFields` + +To get the average discount per store in 2023 for "Laptops", first run a query to partition stores by company and filter discount promotions for "Laptops". Then calculate the average discount percentage within each partitioned result set. + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $unwind: "$promotionEvents.discounts" + }, + + // Filter only Laptops category and events in 2023 + { + $match: { + "promotionEvents.promotionalDates.startDate.Year": 2023, + "promotionEvents.discounts.categoryName": "Laptops" + } + }, + + // Use $setWindowFields to calculate average discount by city + { + $setWindowFields: { + partitionBy: "$company", + output: { + avgDiscount: { + $avg: "$promotionEvents.discounts.discountPercentage", + window: { + documents: ["unbounded", "unbounded"] + } + } + } + } + }, + + // Group by city to return one result per city + { + $group: { + _id: "$company", + avgDiscount: { + $first: "$avgDiscount" + } + } + } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "VanArsdel, Ltd.", + "avgDiscount": 14.461538461538462 + }, + { + "_id": "Proseware, Inc.", + "avgDiscount": 16.25 + }, + { + "_id": "Fabrikam, Inc.", + "avgDiscount": 14.454545454545455 + }, + { + "_id": "Contoso, Ltd.", + "avgDiscount": 14.384615384615385 + }, + { + "_id": "Fourth Coffee", + "avgDiscount": 13.625 + }, + { + "_id": "Trey Research", + "avgDiscount": 17.785714285714285 + }, + { + "_id": "Adatum Corporation", + "avgDiscount": 11.666666666666666 + }, + { + "_id": "Relecloud", + "avgDiscount": 14.375 + }, + { + "_id": "Lakeshore Retail", + "avgDiscount": 15.846153846153847 + }, + { + "_id": "Northwind Traders", + "avgDiscount": 14.2 + }, + { + "_id": "First Up Consultants", + "avgDiscount": 11.25 + }, + { + "_id": "Wide World Importers", + "avgDiscount": 15.571428571428571 + }, + { + "_id": "Tailwind Traders", + "avgDiscount": 16.166666666666668 + } +] +``` diff --git a/api-reference/operators/accumulators/$bottom.md b/api-reference/operators/accumulators/$bottom.md new file mode 100644 index 0000000..e285dba --- /dev/null +++ b/api-reference/operators/accumulators/$bottom.md @@ -0,0 +1,246 @@ +--- +title: $bottom +description: The $bottom operator returns the last document from the query's result set sorted by one or more fields +type: operators +category: accumulators +--- + +# $bottom + +The `$bottom` operator sorts documents on one or more fields specified by the query and returns the last document matching the filtering criteria. + +## Syntax + +```javascript +{ + $bottom: { + output: [listOfFields], + sortBy: { + : < sortOrder > + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`listOfFields`** | The list of fields to be returned from the last document in the result set| +| **`fieldName`** | The field to use for sorting the result set| +| **`sortOrder`** | 1 or -1. 1 implies sorting in ascending order of the value of the field while -1 implies sorting in descending order of the values of the field| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find the store with lowest total sales + +Suppose we want to determine the store within the First Up Consultants company with the lowest total sales, run a query to retrieve documents within the First Up Consultants company, sort the documents in descending order of total sales and return the last document in the sorted result set. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $group: { + _id: "$company", + bottomSales: { + $bottom: { + output: ["$company", "$sales"], + sortBy: { + "sales.revenue": -1 + } + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "First Up Consultants", + "bottomSales": [ + "First Up Consultants", + { + "totalSales": 119, + "salesByCategory": [ + { + "categoryName": "Skirts", + "totalSales": 109 + } + ] + } + ] +}] +``` + +### Example 2: Find the category per store with the lowest sales + +To find the category with the lowest sales per store, run a query to retrieve stores with multiple sales categories, sort the categories in descending order of total sales within each store and return the last document in the sorted result set. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" + }, + { + $match: { + "sales.salesByCategory.totalSales": { + $exists: true + } + } + }, + { + $group: { + _id: "$_id", + storeName: { + $first: "$name" + }, + lowestCategory: { + $bottom: { + sortBy: { + "sales.salesByCategory.totalSales": 1 + }, + output: { + categoryName: "$sales.salesByCategory.categoryName", + totalSales: "$sales.salesByCategory.totalSales" + } + } + } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "b1d86d1f-8705-4157-b64c-a9eda0df4921", + "storeName": "VanArsdel, Ltd. | Baby Products Haven - West Kingfort", + "lowestCategory": { "categoryName": "Baby Monitors", "totalSales": 49585 } + }, + { + "_id": "22e6367e-8341-415f-9795-118d2b522abf", + "storeName": "Adatum Corporation | Outdoor Furniture Mart - Port Simone", + "lowestCategory": { "categoryName": "Outdoor Benches", "totalSales": 4976 } + } +] +``` diff --git a/api-reference/operators/accumulators/$bottomn.md b/api-reference/operators/accumulators/$bottomn.md new file mode 100644 index 0000000..392402e --- /dev/null +++ b/api-reference/operators/accumulators/$bottomn.md @@ -0,0 +1,276 @@ +--- +title: $bottomN +description: The $bottomN operator returns the last N documents from the result sorted by one or more fields +type: operators +category: accumulators +--- + +# $bottomN + +The $bottomN operator sorts documents on one or more fields specified by the query and returns the last N documents matching the filtering criteria. + +## Syntax + +```javascript +{ + $bottomN: { + output: [listOfFields], + sortBy: { + : < sortOrder > + }, + n: < numDocumentsToReturn > + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`listOfFields`** | The list of fields to be returned for the last document in the result set| +| **`fieldName`** | The field to use for sorting the result set| +| **`sortOrder`** | 1 or -1. 1 implies sorting in ascending order of the value of the field while -1 implies sorting in descending order of the values of the field| +| **`n`** | The number of documents to return from the bottom of the sorted result set | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find the bottom two stores by total sales + +To determine the two stores in the First Up Consultants company with the lowest sales, run a query to retrieve stores within the "First Up Consultants" company, sort the resulting documents in descending order of total sales and return the last two documents from the sorted result set. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $group: { + _id: "$company", + bottomSales: { + $bottomN: { + output: ["$company", "$sales"], + sortBy: { + "sales.revenue": -1 + }, + n: 2 + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "First Up Consultants", + "bottomSales": [ + [ + "First Up Consultants", + { + "salesByCategory": [ + { + "categoryName": "Skirts", + "totalSales": 109 + } + ], + "revenue": 109 + } + ], + [ + "First Up Consultants", + { + "salesByCategory": [ + { + "categoryName": "Mirrors", + "totalSales": 120 + } + ], + "revenue": 120 + } + ] + ] +} +] +``` + +### Example 2: Find the bottom two categories by total sales within each store + +To determine the two lowest performing categories by total sales within each store, run a query to retrieve documents with at least two sales categories, sort the categories in descending order of total sales and finally return the bottom two categories per store. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" +}, { + $match: { + "sales.salesByCategory.totalSales": { + $exists: true + } + } +}, { + $group: { + _id: "$_id", + storeName: { + $first: "$name" + }, + categoryCount: { + $sum: 1 + }, + bottomTwoCategories: { + $bottomN: { + n: 2, + sortBy: { + "sales.salesByCategory.totalSales": -1 + }, + output: { + categoryName: "$sales.salesByCategory.categoryName", + totalSales: "$sales.sale" + } + } + } + } +}, { + $match: { + categoryCount: { + $gte: 2 + } + } +}]) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "64ec6589-068a-44a6-be5b-9d37bb0a90f1", + "storeName": "First Up Consultants | Computer Gallery - West Cathrine", + "categoryCount": 8, + "bottomTwoCategories": [ + { + "categoryName": "Gaming Controllers", + "totalSales": null + }, + { + "categoryName": "Network Adapters", + "totalSales": null + } + ] + } +] +``` diff --git a/api-reference/operators/accumulators/$count.md b/api-reference/operators/accumulators/$count.md new file mode 100644 index 0000000..bba00e7 --- /dev/null +++ b/api-reference/operators/accumulators/$count.md @@ -0,0 +1,391 @@ +--- +title: $count +description: The `$count` operator is used to count the number of documents that match a query filtering criteria. +type: operators +category: accumulators +--- + +# $count + +The `$count` operator is used to count the number of documents that match a specified query filter. The count operator is useful for summarizing data or generating counts for specific groupings. + +## Syntax + +```javascript +{ + $count: "" +} +``` + +## Parameters + +| Parameter | Description | +|----------------|-----------------------------------------------------------------------------| +| **``** | The name of the field in the output document where the count will be stored.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Retrieve the count of all documents + +To retrieve the count of documents within the collection, simply run a count query without query filters. + +```javascript +db.stores.aggregate([{ + $count: "totalDocuments" +}]) +``` + +This query returns the following result: + +```json +[ + { + "totalDocuments": 41501 + } +] +``` + +### Example 2: Count documents grouped by a specific field + +To retrieve the count of documents within each sales category, first run a query to group documents by sales category. Then run a count query within each category. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" + }, + { + $group: { + _id: "$sales.salesByCategory.categoryName", + totalCount: { + $count: {} + } + } + } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "Christmas Trees", + "totalCount": 93 + }, + { + "_id": "Nuts", + "totalCount": 83 + }, + { + "_id": "Camping Tables", + "totalCount": 130 + }, + { + "_id": "Music Theory Books", + "totalCount": 52 + }, + { + "_id": "Fortified Wine", + "totalCount": 55 + }, + { + "_id": "Children's Mystery", + "totalCount": 45 + }, + { + "_id": "Short Throw Projectors", + "totalCount": 72 + }, + { + "_id": "Pliers", + "totalCount": 56 + }, + { + "_id": "Bluetooth Headphones", + "totalCount": 104 + }, + { + "_id": "Video Storage", + "totalCount": 80 + }, + { + "_id": "Cleansers", + "totalCount": 68 + }, + { + "_id": "Camera Straps", + "totalCount": 64 + }, + { + "_id": "Carry-On Bags", + "totalCount": 57 + }, + { + "_id": "Disinfectant Wipes", + "totalCount": 85 + }, + { + "_id": "Insignia Smart TVs", + "totalCount": 81 + }, + { + "_id": "Toner Refill Kits", + "totalCount": 38 + }, + { + "_id": "iPads", + "totalCount": 51 + }, + { + "_id": "Memory Foam Mattresses", + "totalCount": 58 + }, + { + "_id": "Storage Baskets", + "totalCount": 68 + }, + { + "_id": "Body Spray", + "totalCount": 96 + } +] +``` + +### Example 3: Count the number of promotion events + +To count the number of promotion events across all stores, first run a query to first unwind by promotion events and then count the distinct promotion events. + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $count: "totalPromotionEvents" + } +]) +``` + +This query returns the following result: + +```json +[ + { + "totalPromotionEvents": 145673 + } +] +``` + +### Example 4: Using `$count` in `$setWindowFields` + +To get sales for Laptops promotions per store, first run a query to filter promotion events for laptops in 2023. Then partition the resulting stores by company. Lastly, run a count query across the partitioned stores to return the results. + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $unwind: "$promotionEvents.discounts" + }, + // Filter only for Laptop discounts in 2023 + { + $match: { + "promotionEvents.promotionalDates.startDate.Year": 2023, + "promotionEvents.discounts.categoryName": "Laptops" + } + }, + // Add sales count by city using window function + { + $setWindowFields: { + partitionBy: "$company", + output: { + salesCount: { + $count: {}, + window: { + documents: ["unbounded", "unbounded"] + } + } + } + } + }, + // Group to return a single result per city + { + $group: { + _id: "$company", + salesCount: { + $first: "$salesCount" + } + } + } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "VanArsdel, Ltd.", + "salesCount": 13 + }, + { + "_id": "Proseware, Inc.", + "salesCount": 12 + }, + { + "_id": "Fabrikam, Inc.", + "salesCount": 11 + }, + { + "_id": "Contoso, Ltd.", + "salesCount": 13 + }, + { + "_id": "Fourth Coffee", + "salesCount": 8 + }, + { + "_id": "Trey Research", + "salesCount": 14 + }, + { + "_id": "Adatum Corporation", + "salesCount": 12 + }, + { + "_id": "Relecloud", + "salesCount": 16 + }, + { + "_id": "Lakeshore Retail", + "salesCount": 13 + }, + { + "_id": "Northwind Traders", + "salesCount": 5 + }, + { + "_id": "First Up Consultants", + "salesCount": 4 + }, + { + "_id": "Wide World Importers", + "salesCount": 7 + }, + { + "_id": "Tailwind Traders", + "salesCount": 12 + } +] +``` diff --git a/api-reference/operators/accumulators/$first.md b/api-reference/operators/accumulators/$first.md new file mode 100644 index 0000000..6123485 --- /dev/null +++ b/api-reference/operators/accumulators/$first.md @@ -0,0 +1,294 @@ +--- +title: $first +description: The $first operator returns the first value in a group according to the group's sorting order. +type: operators +category: accumulators +--- + +# $first + +The $first operator sorts documents on one or more fields specified by the query and returns the first document matching the filtering criteria. If no sorting order is specified, the order is undefined. + +## Syntax + +```javascript +{ + $first: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The expression to evaluate and return the first document from the result set| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Get the least recently updated document + +To retrieve the least recently updated store under the First Up Consultants company, run a query to fetch all documents belonging to the "First Up Consultants" company, sort the resulting documents in ascending order of the lastUpdated field and return the first document in the result set. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $sort: { + lastUpdated: 1 + } +}, { + $group: { + _id: "$company", + firstUpdated: { + $first: "$lastUpdated" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "First Up Consultants", + "firstUpdated": "ISODate('2025-06-11T10:48:01.291Z')" + } +] +``` + +### Example 2: Get first category by sales amount per store + +To retrieve the first category (alphabetically) within each store, run a query to sort the list of sales categories within each store and return the first category from the sorted result set per store. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" + }, + { + $sort: { + "_id": 1, + "sales.salesByCategory.categoryName": 1 + } + }, + { + $group: { + _id: "$_id", + storeName: { + $first: "$name" + }, + totalSales: { + $first: "$sales.totalSales" + }, + firstCategory: { + $first: { + categoryName: "$sales.salesByCategory.categoryName", + categoryTotalSales: "$sales.salesByCategory.totalSales" + } + } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "64ec6589-068a-44a6-be5b-9d37bb0a90f1", + "storeName": "First Up Consultants | Computer Gallery - West Cathrine", + "totalSales": 186829, + "firstCategory": { + "categoryName": "Cases", + "categoryTotalSales": 36386 + } + }, + { + "_id": "14343900-2a5c-44bf-a52b-9efe63579866", + "storeName": "Northwind Traders | Home Improvement Closet - West Evanside", + "totalSales": 35371, + "firstCategory": { + "categoryName": "Doors", + "categoryTotalSales": 21108 + } + } +] +``` + +### Example 3: Get first promotion event per store + +To retrieve the first promotion event for each store, run a query to sort the list of promotion events within each store by startDate and return the first event from the sorted result set per store. + +Get the first promotion event for each store based on start date. + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $sort: { + "_id": 1, + "promotionEvents.promotionalDates.startDate.Year": 1, + "promotionEvents.promotionalDates.startDate.Month": 1, + "promotionEvents.promotionalDates.startDate.Day": 1 + } + }, + { + $group: { + _id: "$_id", + storeName: { + $first: "$name" + }, + firstPromotionEvent: { + $first: { + eventName: "$promotionEvents.eventName", + startYear: "$promotionEvents.promotionalDates.startDate.Year", + startMonth: "$promotionEvents.promotionalDates.startDate.Month" + } + } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "64ec6589-068a-44a6-be5b-9d37bb0a90f1", + "storeName": "First Up Consultants | Computer Gallery - West Cathrine", + "firstPromotionEvent": { + "eventName": "Crazy Markdown Madness", + "startYear": 2024, + "startMonth": 6 + } + }, + { + "_id": "a58d0356-493b-44e6-afab-260aa3296930", + "storeName": "Fabrikam, Inc. | Outdoor Furniture Nook - West Lexie", + "firstPromotionEvent": { + "eventName": "Price Drop Palooza", + "startYear": 2023, + "startMonth": 9 + } + } +] +``` diff --git a/api-reference/operators/accumulators/$firstn.md b/api-reference/operators/accumulators/$firstn.md new file mode 100644 index 0000000..0898947 --- /dev/null +++ b/api-reference/operators/accumulators/$firstn.md @@ -0,0 +1,326 @@ +--- +title: $firstN +description: The $firstN operator sorts documents on one or more fields specified by the query and returns the first N document matching the filtering criteria +type: operators +category: accumulators +--- + +# $firstN + +The `$firstN` operator returns the first N values in a group according to the group's sorting order. If no sorting order is specified, the order is undefined. + +## Syntax + +```javascript +{ + $firstN: { + input: [listOfFields], + sortBy: { + : + }, + n: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`listOfFields`** | The list of fields to be returned for the first N documents in the result set| +| **`fieldName`** | The field to use for sorting the result set| +| **`sortOrder`** | 1 or -1. 1 implies sorting in ascending order of the value of the field while -1 implies sorting in descending order of the values of the field| +| **`n`** | The number of documents to return from the top of the sorted result set | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Use $firstN operator as accumulator to find first two stores by total sales + +To get the top two stores by total sales, run a query to sort all documents in descending order of sales.totalSales and return the first two documents from the sorted result set. + +```javascript +db.stores.aggregate([{ + $sort: { + "sales.totalSales": -1 + } + }, + { + $group: { + _id: null, + topTwoStores: { + $firstN: { + n: 2, + input: { + storeId: "$_id", + storeName: "$name", + totalSales: "$sales.totalSales" + } + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": null, + "topTwoStores": [ + { + "storeId": "ffe155dd-caa2-4ac1-8ec9-0342241a84a3", + "storeName": "Lakeshore Retail | Electronics Stop - Vicentastad", + "totalSales": 399426 + }, + { + "storeId": "cba62761-10f8-4379-9eea-a9006c667927", + "storeName": "Fabrikam, Inc. | Electronics Nook - East Verlashire", + "totalSales": 374845 + } + ] + } +] +``` + +### Example 2: Use $firstN operator as accumulator to find first two categories per store + +To retrieve the first two categories by total sales within each store, run a query to sort all documents in descending order of sales.totalSales within the scope of each store and return the first two categories from the sorted result set per store. + +```javascript +db.stores.aggregate([ + { $unwind: "$sales.salesByCategory" }, + { + $match: { + "sales.salesByCategory.totalSales": { $exists: true } + } + }, + { + $sort: { + "_id": 1, + "sales.salesByCategory.totalSales": -1 + } + }, + { + $group: { + _id: "$_id", + storeName: { $first: "$name" }, + categoryCount: { $sum: 1 }, + firstTwoCategories: { + $push: { + categoryName: "$sales.salesByCategory.categoryName", + totalSales: "$sales.salesByCategory.totalSales" + } + } + } + }, + { + $project: { + storeName: 1, + categoryCount: 1, + firstTwoCategories: { $slice: ["$firstTwoCategories", 2] } + } + }, + { + $match: { + categoryCount: { $gte: 2 } + } + }, + { $limit: 2 } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "2e07b49d-1730-491b-b847-44b6a34812c1", + "storeName": "VanArsdel, Ltd. | Electronics Market – North Bransonborough", + "categoryCount": 3, + "firstTwoCategories": [ + { + "categoryName": "iPads", + "totalSales": 37113 + }, + { + "categoryName": "Laptops", + "totalSales": 9175 + } + ] + }, + { + "_id": "1bec7539-dc75-4f7e-b4e8-afdf8ff2f234", + "storeName": "Adatum Corporation | Health Food Market – East Karina", + "categoryCount": 2, + "firstTwoCategories": [ + { + "categoryName": "Protein Bars", + "totalSales": 49900 + }, + { + "categoryName": "Superfoods", + "totalSales": 39683 + } + ] + } +] +``` + +### Example 3: Use `firstN` operator as array-expression to find first three sales categories + +The example demonstrates the operator usage to find the first three sales categories for analysis. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + totalSales: "$sales.totalSales", + firstThreeCategories: { + $firstN: { + input: "$sales.salesByCategory", + n: 3 + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "totalSales": 165000, + "firstThreeCategories": [ + { + "categoryName": "Sound Bars", + "totalSales": 2120 + }, + null, + { + "categoryName": "Game Controllers", + "totalSales": 43522 + } + ] + } +] +``` diff --git a/api-reference/operators/accumulators/$last.md b/api-reference/operators/accumulators/$last.md new file mode 100644 index 0000000..86cb9fb --- /dev/null +++ b/api-reference/operators/accumulators/$last.md @@ -0,0 +1,208 @@ +--- +title: $last +description: The $last operator returns the last document from the result sorted by one or more fields +type: operators +category: accumulators +--- + +# $last + +The `$last` operator sorts documents on one or more fields specified by the query and returns the last document matching the filtering criteria. + +## Syntax + +```javascript +{ + "$last": +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The expression to evaluate and return the last document from the result set| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Get the last updated store within a company + +To retrieve the more recently updated store within the First Up Consultants company, run a query to fetch all stores within First Up Consultants, sort the documents in ascending order of the lastUpdated field and return the last document from the sorted results. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $sort: { + lastUpdated: 1 + } +}, { + $group: { + _id: "$company", + lastUpdated: { + $last: "$lastUpdated" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "First Up Consultants", + "lastUpdated": "ISODate('2024-12-31T13:01:19.097Z')" + } +] +``` + +### Example 2 - Using the window operator + +To retrieve the more recently updated store within each company, run a query to partition the results by the company field and sort the documents within each partition in ascending order of lastUpdated field and return the sorted results per partition. + +```javascript +db.stores.aggregate([{ + $setWindowFields: { + partitionBy: "$company", + sortBy: { + lastUpdated: 1 + }, + output: { + lastUpdatedDateForStore: { + $last: "$lastUpdated", + window: { + documents: ["current", "unbounded"] + } + } + } + } +}]) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "First Up Consultants", + "lastUpdated": "ISODate('2024-12-31T13:01:19.097Z')" + } +] +``` diff --git a/api-reference/operators/accumulators/$lastn.md b/api-reference/operators/accumulators/$lastn.md new file mode 100644 index 0000000..c62ea9b --- /dev/null +++ b/api-reference/operators/accumulators/$lastn.md @@ -0,0 +1,413 @@ +--- +title: $lastN +description: The $lastN accumulator operator returns the last N values in a group of documents. +type: operators +category: accumulators +--- + +# $lastN + +The `$lastN` accumulator operator returns the last N values in a group of documents for a specified expression. It's useful when you need to retrieve multiple final values from a sorted collection rather than just the single last value. + +## Syntax + +```javascript +{ + $group: { + _id: < expression > , + < field >: { + $lastN: { + n: < number >, + input: < expression > + } + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`n`** | The number of values to return. Must be a positive integer. | +| **`input`** | The expression that specifies the field or value to return the last N occurrences of. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Use $lastN as accumulator to find last two promotion events by store + +To retrieve the last two promotion events for each store, run a query to sort promotion events in ascending order of their start dates, group the sorted events by store and return the last two events within each store. + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $sort: { + "promotionEvents.promotionalDates.startDate.Year": 1, + "promotionEvents.promotionalDates.startDate.Month": 1, + "promotionEvents.promotionalDates.startDate.Day": 1 + } + }, + { + $group: { + _id: "$_id", + storeName: { + $last: "$name" + }, + lastTwoPromotions: { + $lastN: { + input: "$promotionEvents.eventName", + n: 2 + } + }, + lastTwoPromotionDates: { + $lastN: { + input: "$promotionEvents.promotionalDates.startDate", + n: 2 + } + } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "e28fff9b-a8fb-4ac9-bb37-dea60d2a7d32", + "storeName": "Lakeshore Retail | Outdoor Furniture Collection - Erdmanside", + "lastTwoPromotions": [ + "Big Bargain Bash", + "Spectacular Savings Showcase" + ], + "lastTwoPromotionDates": [ + { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + { + "Year": 2024, + "Month": 6, + "Day": 23 + } + ] + }, + { + "_id": "1bec7539-dc75-4f7e-b4e8-afdf8ff2f234", + "storeName": "Adatum Corporation | Health Food Market - East Karina", + "lastTwoPromotions": [ + "Price Slash Spectacular", + "Spectacular Savings Showcase" + ], + "lastTwoPromotionDates": [ + { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + { + "Year": 2024, + "Month": 6, + "Day": 23 + } + ] + } +] +``` + +### Example 2: Use $lastN as accumulator to find the three highest selling categories of sales + +To retrieve the highest selling sales categories per store, run a query to sort sales categories in ascending order of sales volume, group the sorted results by store and return the last three categories per store. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" + }, + { + $sort: { + "sales.salesByCategory.totalSales": 1 + } + }, + { + $group: { + _id: "$_id", + storeName: { + $last: "$name" + }, + top3Categories: { + $lastN: { + input: "$sales.salesByCategory.categoryName", + n: 3 + } + }, + top3SalesAmounts: { + $lastN: { + input: "$sales.salesByCategory.totalSales", + n: 3 + } + } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "22e6367e-8341-415f-9795-118d2b522abf", + "storeName": "Adatum Corporation | Outdoor Furniture Mart - Port Simone", + "top3Categories": [ + "Outdoor Benches" + ], + "top3SalesAmounts": [ + 4976 + ] + }, + { + "_id": "a00a3ccd-49a2-4e43-b0d9-e56b96113ed0", + "storeName": "Wide World Importers | Smart Home Deals - Marcuschester", + "top3Categories": [ + "Smart Thermostats", + "Smart Plugs" + ], + "top3SalesAmounts": [ + 38696, + 633 + ] + } +] +``` + +### Example 3: Use $lastN operator as array-expression to get last two promotion events + +The example demonstrates the operator usage to find the last or most recent two promotion events from a store. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + lastTwoPromotions: { + $lastN: { + input: "$promotionEvents", + n: 2 + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "lastTwoPromotions": [ + { + "eventName": "Grand Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 6, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Remote Controls", + "discountPercentage": 7 + }, + { + "categoryName": "Televisions", + "discountPercentage": 11 + }, + { + "categoryName": "Business Projectors", + "discountPercentage": 13 + }, + { + "categoryName": "Laser Projectors", + "discountPercentage": 6 + }, + { + "categoryName": "Projectors", + "discountPercentage": 6 + }, + { + "categoryName": "Projector Screens", + "discountPercentage": 24 + } + ] + }, + { + "eventName": "Major Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Sound Bars", + "discountPercentage": 9 + }, + { + "categoryName": "VR Games", + "discountPercentage": 7 + }, + { + "categoryName": "Xbox Games", + "discountPercentage": 25 + }, + { + "categoryName": "Projector Accessories", + "discountPercentage": 18 + }, + { + "categoryName": "Mobile Games", + "discountPercentage": 8 + }, + { + "categoryName": "Projector Cases", + "discountPercentage": 22 + } + ] + } + ] + } +] +``` diff --git a/api-reference/operators/accumulators/$max.md b/api-reference/operators/accumulators/$max.md new file mode 100644 index 0000000..0255ba5 --- /dev/null +++ b/api-reference/operators/accumulators/$max.md @@ -0,0 +1,432 @@ +--- +title: $max +description: The $max operator returns the maximum value from a set of input values. +type: operators +category: accumulators +--- + +# $max + +The `$max` operator returns the maximum value of a set of input values. + +When used as a field update operator, the `$max` operator updates the value of a field to a specified value if the specified value is greater than the current value of the field. If the field does not exist, `$max` creates the field and sets it to the specified value. + +## Syntax + +```javascript +$max: +``` + +When used as a field update operator: + +```javascript +{ + $max: { + : , + : , + ... + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid expression that resolves to a value. The `$max` operator evaluates this expression to determine the maximum value. | + +When used as a field update operator: + +| Parameter | Description | +| --- | --- | +| **`field`** | The name of the field to update with the maximum value. | +| **`value`** | The value to compare with the current field value. The field will be updated only if this value is larger. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculate the highest sales by category + +To calculate the highest sales within each category, first run a query to group all documents by sales category. Then run a $max query to retrieve the highest sales within each category across all stores. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" + }, + { + $group: { + _id: "$sales.salesByCategory.categoryName", + maxSales: { + $max: "$sales.salesByCategory.totalSales" + } + } + } +]) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "Christmas Trees", + "maxSales": 49697 + }, + { + "_id": "Nuts", + "maxSales": 48020 + }, + { + "_id": "Camping Tables", + "maxSales": 48568 + }, + { + "_id": "Music Theory Books", + "maxSales": 46133 + }, + { + "_id": "Fortified Wine", + "maxSales": 49912 + } +] +``` + +### Example 2: Using `$max` in `$bucket` + +To retrieve the highest sales within buckets of sales boundaries: + +```javascript +db.stores.aggregate([{ + $bucket: { + groupBy: "$sales.totalSales", + boundaries: [0, 1000, 5000, 10000], + default: "Other", + output: { + maxSales: { + $max: "$sales.totalSales" + } + } + } +}]) +``` + +This query returns the following results: + +```json +[ + { + "_id": 1000, + "maxSales": 4996 + }, + { + "_id": "Other", + "maxSales": 404106 + }, + { + "_id": 0, + "maxSales": 995 + }, + { + "_id": 5000, + "maxSales": 9999 + } +] +``` + +### Example 3: Using `$max` in `$setWindowFields` + +To get the highest discount for laptops in 2023, first run a query to unwind just promotion events and filter on the chosen category. Then partition the resulting documents by company and calculate the highest discount percentage within each resulting partition. + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $unwind: "$promotionEvents.discounts" + }, + // Filter only Laptops category and events in 2023 + { + $match: { + "promotionEvents.promotionalDates.startDate.Year": 2023, + "promotionEvents.discounts.categoryName": "Laptops" + } + }, + // Use $setWindowFields to calculate average discount by city + { + $setWindowFields: { + partitionBy: "$company", + output: { + maxDiscount: { + $max: "$promotionEvents.discounts.discountPercentage", + window: { + documents: ["unbounded", "unbounded"] + } + } + } + } + }, + // Group by city to return one result per city + { + $group: { + _id: "$company", + maxDiscount: { + $first: "$maxDiscount" + } + } + } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "Proseware, Inc.", + "maxDiscount": 24 + }, + { + "_id": "Fabrikam, Inc.", + "maxDiscount": 23 + }, + { + "_id": "Contoso, Ltd.", + "maxDiscount": 24 + } +] +``` + +### Example 4: Setting maximum staff capacity (field update operator) + +To update the full time staff to 10 only if the current full time staff count is lower, use the $max operator on the field to perform the update. Since the current `fullTime` value is 3, and 10 is greater than 3, the field will be updated to 10. + +```javascript +db.stores.updateOne( + { _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" }, + { + $max: { + "staff.totalStaff.fullTime": 10 + } + } +) +``` + +### Example 5: Multiple field updates (field update operator) + +To update multiple fields with maximum values, use the $max operator with multiple fields and their corresponding max values to set. + +```javascript +db.stores.updateOne( + { _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" }, + { + $max: { + "staff.totalStaff.partTime": 1, + "sales.totalSales": 50000 + } + } +) +``` + +In this case: + +- `partTime` (2) will remain 2 since 1 < 2 (no change) +- `totalSales` (31211) will be updated to 50000 since 50000 > 31211 + +### Example 6: Creating new fields (field update operator) + +If a field doesn't exist, `$max` creates it with the specified value. + +```javascript +db.stores.updateOne( + { _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" }, + { + $max: { + "staff.maxStaffCapacity": 25, + "sales.peakSalesRecord": 100000 + } + } +) +``` + +### Example 7: Updating array elements (field update operator) + +Update maximum values within array elements using positional operators. + +```javascript +db.stores.updateOne( + { + _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66", + "sales.salesByCategory.categoryName": "Phone Mounts" + }, + { + $max: { + "sales.salesByCategory.$.totalSales": 12000 + } + } +) +``` + +### Example 8: Tracking peak performance (field update operator) + +Set peak performance metrics that only update when exceeded. + +```javascript +db.stores.updateOne( + { _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" }, + { + $max: { + "performance.peakDailySales": 5000, + "performance.maxCustomersPerDay": 150, + "performance.highestSalesMonth": 45000 + } + } +) +``` + +After these field update operations, the updated document is: + +```json +{ + "_id": "f2a8c190-28e4-4e14-9d8b-0256e53dca66", + "name": "Fabrikam, Inc. | Car Accessory Outlet - West Adele", + "staff": { + "totalStaff": { + "fullTime": 10, + "partTime": 2 + }, + "maxStaffCapacity": 25 + }, + "sales": { + "totalSales": 50000, + "peakSalesRecord": 100000, + "salesByCategory": [ + { + "categoryName": "Phone Mounts", + "totalSales": 12000 + }, + { + "categoryName": "Dash Cameras", + "totalSales": 22300 + } + ] + }, + "performance": { + "peakDailySales": 5000, + "maxCustomersPerDay": 150, + "highestSalesMonth": 45000 + }, + "lastPromotionDate": ISODate("2024-12-31T00:00:00.000Z"), + "inventoryDeadline": ISODate("2024-06-30T00:00:00.000Z") +} +``` diff --git a/api-reference/operators/accumulators/$maxn.md b/api-reference/operators/accumulators/$maxn.md new file mode 100644 index 0000000..b28cde3 --- /dev/null +++ b/api-reference/operators/accumulators/$maxn.md @@ -0,0 +1,255 @@ +--- +title: $maxN +description: The $maxN opertor retrieves the top N values based on a specified filtering criteria +type: operators +category: accumulators +--- + +# $maxN + +The `$maxN` operator is used to retrieve the top N values for a field based on a specified filtering criteria. + +## Syntax + +```javascript +$maxN: { + input: < field or expression > , + n: < number of values to retrieve > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | Specifies the field or expression to evaluate for maximum values. | +| **`n`** | Specifies the number of maximum values to retrieve. Must be a positive integer. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ], + "company": "Lakeshore Retail", + "city": "Port Cecile", + "lastUpdated": { + "$date": "2024-12-11T10:21:58.274Z" + } +} +``` + +### Example 1: Use `$maxN` as `accumulator` to retrieve top two sales categories + +This query retrieves the top two sales categories with the high-performing categories or aggregate top categories across stores. + +```javascript +db.stores.aggregate([{ + $project: { + topSalesCategories: { + $maxN: { + input: "$sales.salesByCategory", + n: 2 + } + } + } + }, + { + $limit: 4 + } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "topSalesCategories": [ + { + "categoryName": "Stockings", + "totalSales": 25731 + } + ] + }, + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "topSalesCategories": [ + { + "categoryName": "Markers", + "totalSales": 3927 + } + ] + }, + { + "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", + "topSalesCategories": [ + { + "categoryName": "Storage Boxes", + "totalSales": 2236 + } + ] + }, + { + "_id": "94792a4c-4b03-466b-91f6-821c4a8b2aa4", + "topSalesCategories": [ + { + "categoryName": "Travel Backpacks", + "totalSales": 13189 + }, + { + "categoryName": "Suitcases", + "totalSales": 37858 + } + ] + } +] +``` + +### Example 2: Using `$maxN` in `$setWindowFields` + +This query retrieves the top N discounts for "Laptops" in 2023 per city. This query filters for "Laptops" discount entries in 2023 and then groups the resulting documents by city. + +```javascript +db.stores.aggregate([ + { $unwind: "$promotionEvents" }, + { $unwind: "$promotionEvents.discounts" }, + { + $match: { + "promotionEvents.discounts.categoryName": "Laptops", + "promotionEvents.promotionalDates.startDate.Year": 2023 + } + }, + { + $group: { + _id: "$city", + allDiscounts: { + $push: "$promotionEvents.discounts.discountPercentage" + } + } + }, + { + $project: { + topDiscounts: { + $slice: [ + { $sortArray: { input: "$allDiscounts", sortBy: -1 } }, + 3 // Top N discounts + ] + } + } + } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "Lake Margareteland", + "topDiscounts": [ + 18 + ] + }, + { + "_id": "Horacetown", + "topDiscounts": [ + 13 + ] + }, + { + "_id": "D'Amoreside", + "topDiscounts": [ + 9 + ] + } +] +``` + +### Example 3: Using `$maxN` operator as array-expression to find top three sales categories + +This query retrieves the top three sales values from all sales categories. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + topThreeSales: { + $maxN: { + input: "$sales.salesByCategory.totalSales", + n: 3 + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "topThreeSales": [43522, 32272, 28946] + } +] +``` diff --git a/api-reference/operators/accumulators/$median.md b/api-reference/operators/accumulators/$median.md new file mode 100644 index 0000000..ae2df0f --- /dev/null +++ b/api-reference/operators/accumulators/$median.md @@ -0,0 +1,193 @@ +--- +title: $median +description: The $median operator calculates the median value of a numeric field in a group of documents. +type: operators +category: accumulators +--- + +# $median usage on DocumentDB + +The `$median` accumulator operator calculates the median value of a numeric field in a group of documents. + +## Syntax + +```javascript +{ + $group: { + _id: < expression > , + medianValue: { + $median: { + input: < field or expression > , + method: < > + } + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The field or expression from which to calculate the median. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculate the median sales volume + +To calculate the median sales volume within each category, first group the documents by the distinct sales categories, then calculate the median sales within each grouped category. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" +}, { + $group: { + _id: "$sales.salesByCategory.categoryName", + medianSales: { + $median: { + "input": "$sales.salesByCategory.totalSales", + "method": "approximate" + } + } + } +}]) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "Light Bulbs", + "medianSales": 24845 + }, + { + "_id": "Christmas Trees", + "medianSales": 28210 + }, + { + "_id": "Ukuleles", + "medianSales": 27295 + }, + { + "_id": "GPUs", + "medianSales": 19813 + }, + { + "_id": "Towels", + "medianSales": 27771 + } +] +``` diff --git a/api-reference/operators/accumulators/$min.md b/api-reference/operators/accumulators/$min.md new file mode 100644 index 0000000..8dc972f --- /dev/null +++ b/api-reference/operators/accumulators/$min.md @@ -0,0 +1,485 @@ +--- +title: $min +description: The $min operator retrieves the minimum value for a specified field +type: operators +category: accumulators +--- + +# $min + +The `$min` operator is used within aggregation stages like `$group`, `$bucket`, `$bucketAuto`, or `$setWindowFields`. The min operator is particularly useful in summarizing data or finding the smallest value in a dataset. + +When used as a field update operator, `$min` operator updates the value of a field to a specified value if the specified value is less than the current value of the field. If the field does not exist, `$min` creates the field and sets it to the specified value. + +## Syntax + +```javascript +$min: +``` + +The `` can be a field path or an aggregation expression that specifies the values to be considered for the minimum calculation. + +As a field update operator: + +```javascript +{ + $min: { + : , + : , + ... + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Specifies the field or computed value to determine the minimum value. | + +As a field update operator: + +| Parameter | Description | +| --- | --- | +| **`field`** | The name of the field to update with the minimum value. | +| **`value`** | The value to compare with the current field value. The field will be updated only if this value is smaller. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ], + "company": "Lakeshore Retail", + "city": "Port Cecile", + "lastUpdated": { + "$date": "2024-12-11T10:21:58.274Z" + } +} +``` + +### Example 1: Using `$min` in `$group` + +This query calculates the minimum sales value for each category in the `sales.salesByCategory` array by first grouping documents by sales category and then calculating the minimum sales volume within each category. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" + }, + { + $group: { + _id: "$sales.salesByCategory.categoryName", + minSales: { + $min: "$sales.salesByCategory.totalSales" + } + } + } +]) +``` + +This query returns the following results. + +```json +[ + { + "_id": "Christmas Trees", + "minSales": 391 + }, + { + "_id": "Nuts", + "minSales": 257 + }, + { + "_id": "Camping Tables", + "minSales": 171 + }, + { + "_id": "Music Theory Books", + "minSales": 323 + }, + { + "_id": "Fortified Wine", + "minSales": 521 + }, + { + "_id": "Children's Mystery", + "minSales": 1470 + }, + { + "_id": "Short Throw Projectors", + "minSales": 111 + }, + { + "_id": "Pliers", + "minSales": 1981 + }, + { + "_id": "Bluetooth Headphones", + "minSales": 465 + }, + { + "_id": "Video Storage", + "minSales": 1568 + }, + { + "_id": "Cleansers", + "minSales": 170 + }, + { + "_id": "Camera Straps", + "minSales": 127 + }, + { + "_id": "Carry-On Bags", + "minSales": 149 + }, + { + "_id": "Disinfectant Wipes", + "minSales": 647 + }, + { + "_id": "Insignia Smart TVs", + "minSales": 451 + }, + { + "_id": "Toner Refill Kits", + "minSales": 3525 + }, + { + "_id": "iPads", + "minSales": 325 + }, + { + "_id": "Storage Baskets", + "minSales": 1151 + }, + { + "_id": "Memory Foam Mattresses", + "minSales": 422 + }, + { + "_id": "Body Spray", + "minSales": 448 + } +] +``` + +### Example 2: Using `$min` in `$bucket` + +This query creates buckets based on sales values and calculates the minimum sales value for each bucket. + +```javascript +db.stores.aggregate([{ + $bucket: { + groupBy: "$sales.totalSales", + boundaries: [0, 1000, 5000, 10000], + default: "Other", + output: { + minSales: { + $min: "$sales.totalSales" + } + } + } +}]) +``` + +This query returns the following results. + +```json +[ + { + "_id": 1000, + "minSales": 1000 + }, + { + "_id": "Other", + "minSales": null + }, + { + "_id": 0, + "minSales": 108 + }, + { + "_id": 5000, + "minSales": 5001 + } +] +``` + +### Example 3: Using `$min` in `$setWindowFields` + +This query retrieves the minimum discount for "Laptops" by company, in the year 2023: + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $unwind: "$promotionEvents.discounts" + }, + + // Filter only Laptops category and events in 2023 + { + $match: { + "promotionEvents.promotionalDates.startDate.Year": 2023, + "promotionEvents.discounts.categoryName": "Laptops" + } + }, + + // Use $setWindowFields to calculate average discount by city + { + $setWindowFields: { + partitionBy: "$company", + output: { + minDiscount: { + $min: "$promotionEvents.discounts.discountPercentage", + window: { + documents: ["unbounded", "unbounded"] + } + } + } + } + }, + + // Group by city to return one result per city + { + $group: { + _id: "$company", + minDiscount: { + $first: "$minDiscount" + } + } + } +]) +``` + +This query returns the following results. + +```json +[ + { + "_id": "VanArsdel, Ltd.", + "minDiscount": 6 + }, + { + "_id": "Proseware, Inc.", + "minDiscount": 8 + }, + { + "_id": "Fabrikam, Inc.", + "minDiscount": 5 + }, + { + "_id": "Contoso, Ltd.", + "minDiscount": 5 + }, + { + "_id": "Fourth Coffee", + "minDiscount": 6 + }, + { + "_id": "Trey Research", + "minDiscount": 7 + }, + { + "_id": "Adatum Corporation", + "minDiscount": 5 + }, + { + "_id": "Relecloud", + "minDiscount": 5 + }, + { + "_id": "Lakeshore Retail", + "minDiscount": 7 + }, + { + "_id": "Northwind Traders", + "minDiscount": 8 + }, + { + "_id": "First Up Consultants", + "minDiscount": 9 + }, + { + "_id": "Wide World Importers", + "minDiscount": 10 + }, + { + "_id": "Tailwind Traders", + "minDiscount": 5 + } +] +``` + +### Example 4: Setting minimum staff requirements (field update operator) + +To set a minimum staff requirement, update the full time stagg count only if the current value of the field is higher. Since the current `fullTime` value is 14, and 10 is less than 14, the field will be updated to 10. + +```javascript +db.stores.updateOne( + { _id: "26afb024-53c7-4e94-988c-5eede72277d5" }, + { + $min: { + "staff.totalStaff.fullTime": 10 + } + } +) +``` + +### Example 5: Multiple field updates (field update operator) + +To update multiple fields with minimum values simultaneously, use the $min operator with multiple fields and corresponding min values. + +```javascript +db.stores.updateOne( + { _id: "26afb024-53c7-4e94-988c-5eede72277d5" }, + { + $min: { + "staff.totalStaff.partTime": 12, + "sales.totalSales": 50000 + } + } +) +``` + +In this case: + +- `partTime` (8) will be updated to 8 since 12 > 8 (no change) +- `totalSales` (83865) will be updated to 50000 since 50000 < 83865 + +### Example 6: Creating new fields (field update operator) + +If a field doesn't exist, `$min` creates it with the specified value. + +```javascript +db.stores.updateOne( + { _id: "26afb024-53c7-4e94-988c-5eede72277d5" }, + { + $min: { + "staff.minStaffRequired": 15, + "sales.minimumSalesTarget": 30000 + } + } +) +``` + +### Example 7: Working with Dates (field update operator) + +Set minimum dates for tracking earliest events. + +```javascript +db.stores.updateOne( + { _id: "26afb024-53c7-4e94-988c-5eede72277d5" }, + { + $min: { + "lastInventoryCheck": new Date("2024-01-15"), + "firstSaleDate": new Date("2023-06-01") + } + } +) +``` + +### Example 8: Updating array elements (field update operator) + +Update minimum values within array elements using positional operators. + +```javascript +db.stores.updateOne( + { + _id: "26afb024-53c7-4e94-988c-5eede72277d5", + "sales.salesByCategory.categoryName": "Lavalier Microphones" + }, + { + $min: { + "sales.salesByCategory.$.totalSales": 40000 + } + } +) +``` + +After these field update operations, the updated document is: + +```json +{ + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "staff": { + "totalStaff": { + "fullTime": 10, + "partTime": 8 + }, + "minStaffRequired": 15 + }, + "sales": { + "totalSales": 50000, + "minimumSalesTarget": 30000, + "salesByCategory": [ + { + "categoryName": "Lavalier Microphones", + "totalSales": 40000 + }, + { + "categoryName": "Wireless Microphones", + "totalSales": 39691 + } + ] + }, + "lastInventoryCheck": ISODate("2024-01-15T00:00:00.000Z"), + "firstSaleDate": ISODate("2023-06-01T00:00:00.000Z") +} +``` diff --git a/api-reference/operators/accumulators/$minn.md b/api-reference/operators/accumulators/$minn.md new file mode 100644 index 0000000..b9ea429 --- /dev/null +++ b/api-reference/operators/accumulators/$minn.md @@ -0,0 +1,308 @@ +--- +title: $minN +description: The $minN operator retrieves the bottom N values based on a specified filtering criteria +type: operators +category: accumulators +--- + +# $minN + +The `$minN` operator is used to retrieve the bottom N values for a field based on a specified filtering criteria. + +## Syntax + +```javascript +$minN: { + input: < field or expression > , + n: < number of values to retrieve > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | Specifies the field or expression to evaluate for minimum values. | +| **`n`** | Specifies the number of minimum values to retrieve. Must be a positive integer. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ], + "company": "Lakeshore Retail", + "city": "Port Cecile", + "lastUpdated": { + "$date": "2024-12-11T10:21:58.274Z" + } +} +``` + +### Example 1: Retrieve bottom two sales categories + +This query retrieves the bottom two sales categories per store with the lowest sales volume. Run a query using the $minN operator on the nested salesCategory field. + +```javascript +db.stores.aggregate([{ + $project: { + bottomSalesCategories: { + $minN: { + input: "$sales.salesByCategory", + n: 2 + } + } + } + }, + { + $limit: 4 + } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "bottomSalesCategories": [ + { + "categoryName": "Stockings", + "totalSales": 25731 + } + ] + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "bottomSalesCategories": [ + { + "categoryName": "Lamps", + "totalSales": 19880 + }, + { + "categoryName": "Rugs", + "totalSales": 20055 + } + ] + }, + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "bottomSalesCategories": [ + { + "categoryName": "Markers", + "totalSales": 3927 + } + ] + }, + { + "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", + "bottomSalesCategories": [ + { + "categoryName": "Storage Boxes", + "totalSales": 2236 + } + ] + } +] +``` + +### Example 2 - Using $minN with $setWindowFields + +To get the bottom two lists of sales categories by sales volume across all stores within the "First Up Consultants" company, first run a query to partition the stores by the company. Then, use the $minN operator to determine the two categories with the lowest sales within each partition. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $setWindowFields: { + partitionBy: "$company", + sortBy: { + "sales.totalSales": -1 + }, + output: { + minTwoBySales: { + $minN: { + input: "$sales.totalSales", + n: 2 + } + } + } + } +}, { + $project: { + company: 1, + name: 1, + minCategoriesBySales: 1 + } +}]) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "a0386810-b6f8-4b05-9d60-e536fb2b0026", + "name": "First Up Consultants | Electronics Stop - South Thelma", + "company": "First Up Consultants", + "minCategoriesBySales": [ + [ + { + "categoryName": "3D Printers", + "totalSales": 20882 + }, + { + "categoryName": "Phone Mounts", + "totalSales": 13624 + }, + { + "categoryName": "Prepaid Phones", + "totalSales": 7182 + }, + { + "categoryName": "MacBooks", + "totalSales": 10541 + }, + { + "categoryName": "Chargers", + "totalSales": 37542 + }, + { + "categoryName": "Student Laptops", + "totalSales": 43977 + }, + { + "categoryName": "Screen Protectors", + "totalSales": 14648 + }, + { + "categoryName": "Photo Printers", + "totalSales": 40064 + }, + { + "categoryName": "Printer Ink", + "totalSales": 30784 + }, + { + "categoryName": "Smartphone Cases", + "totalSales": 30468 + }, + { + "categoryName": "Printer Drums", + "totalSales": 34980 + }, + { + "categoryName": "Desktops", + "totalSales": 3890 + } + ], + [ + { + "categoryName": "4K Camcorders", + "totalSales": 10466 + }, + { + "categoryName": "Tripods", + "totalSales": 30942 + }, + { + "categoryName": "Camcorder Accessories", + "totalSales": 25601 + } + ] + ] + } +] +``` + +### Example 3 - Using $minN operator as array-expression to get lowest two sales values + +This query extracts the two lowest sales values for a specific store document. + +```javascript +db.stores.aggregate([ + { $match: {_id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + lowestTwoSales: { + $minN: { + input: "$sales.salesByCategory.totalSales", + n: 2 + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "lowestTwoSales": [28946, 3000] + } +] +``` diff --git a/api-reference/operators/accumulators/$percentile.md b/api-reference/operators/accumulators/$percentile.md new file mode 100644 index 0000000..c3dfb48 --- /dev/null +++ b/api-reference/operators/accumulators/$percentile.md @@ -0,0 +1,212 @@ +--- +title: $percentile +description: The $percentile operator calculates the percentile of numerical values that match a filtering criteria +type: operators +category: accumulators +--- + +# $percentile + +The `$percentile` operator calculates the percentile of numerical values that match a filtering criteria. This operator is particularly useful for identifying statistical thresholds, such as median or percentiles. + +## Syntax + +```javascript +$percentile: { + input: < field or expression > , + p: [ < percentile values > ], + method: < method > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | Specifies the numerical data to calculate the percentile from. | +| **`p`** | An array of percentile values (between 0 and 1) to calculate. | +| **`method`** | Specifies the interpolation method to use. Valid values are `"approximate"` and `"continuous"`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculate the 50th percentile of sales volume + +This query calculates the 50th percentile (median) of total sales volume within each sales category across all stores. + +```javascript +db.stores.aggregate([{ + $unwind: "$sales.salesByCategory" + }, + { + $group: { + _id: null, + medianSales: { + $percentile: { + input: "$sales.salesByCategory.totalSales", + p: [0.5], + method: "approximate" + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": null, + "medianSales": [ + 25070.449624139295 + ] + } +] +``` + +### Example 2: Calculate multiple percentiles + +This query calculates the 25th, 50th, and 75th percentiles of the total sales across all stores. + +```javascript +db.stores.aggregate([{ + $group: { + _id: null, + percentiles: { + $percentile: { + input: "$sales.fullSales", + p: [0.25, 0.5, 0.75], + method: "approximate" + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": null, + "percentiles": [ + 3700, + 3700, + 3700 + ] + } +] +``` diff --git a/api-reference/operators/accumulators/$stddevpop.md b/api-reference/operators/accumulators/$stddevpop.md new file mode 100644 index 0000000..b1b8a47 --- /dev/null +++ b/api-reference/operators/accumulators/$stddevpop.md @@ -0,0 +1,284 @@ +--- +title: $stddevpop +description: The $stddevpop operator calculates the standard deviation of the specified values +type: operators +category: accumulators +--- + +# $stddevpop + +The `$stddevpop` operator calculates the standard deviation of the specified values. The operator can only calculate the standard deviation of numeric values. + +## Syntax + +```javascript +{ + $stddevpop: {fieldName} +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`fieldName`** | The field whose values are used to calculate the standard deviation| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the standard deviation of total sales + +To calculate the standard deviation of the total sales across all sales categories for stores belonging to "Fourth Coffee", first filter on the company field, then calculate the total sales across all resulting stores using stddevpop and return the aggregated result. + +```javascript +db.stores.aggregate([{ + $match: { + company: "Fourth Coffee" + } +}, { + $group: { + _id: "$company", + stdDev: { + $stdDevPop: "$sales.totalSales" + } + } +}])[{ + _id: 'Fourth Coffee', + stdDev: 0 +}] +``` + +This query returns the following result: + +```json +[ + { + "_id": "Fourth Coffee", + "stdDev": 39133.27057120701 + } +] +``` + +### Example 2 - Calculate the standard deviation of a field with a single value + +To calculate the standard deviation of a field with only one distinct value, the standard deviation is 0. This query groups documents corresponding to the "Fourth Company". Each store contains a single document and only one distinct value for total sales. + +```javascript +db.stores.aggregate([{ + $match: { + company: "Fourth Coffee" + } +}, { + $group: { + _id: "$name", + stdDev: { + $stdDevPop: "$sales.totalSales" + } + } +}]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "Fourth Coffee | Outdoor Equipment Collection - Kochview", + "stdDev": 0 + }, + { + "_id": "Fourth Coffee | Grocery Hub - Brakusborough", + "stdDev": 0 + }, + { + "_id": "Fourth Coffee | Pet Supply Nook - Lake Armanimouth", + "stdDev": 0 + }, + { + "_id": "Fourth Coffee | Beauty Product Nook - Emmytown", + "stdDev": 0 + }, + { + "_id": "Fourth Coffee | Bed and Bath Closet - Legroston", + "stdDev": 0 + }, + { + "_id": "Fourth Coffee | Automotive Part Collection - Cassinport", + "stdDev": 0 + } +] +``` + +### Example 3 - Calculate the standard deviation for a field when using window operators + +This query calculates the standard deviation of total sales for stores belonging to the "First Up Consultants" company from the first to the current document in the result set. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + }, + $and: [{ + lastUpdated: { + $gt: ISODate("2024-09-01T03:06:24.180Z") + } + }, { + lastUpdated: { + "$lt": ISODate("2025-09-30T03:55:17.557Z") + } + }] + } +}, { + $setWindowFields: { + partitionBy: "$company", + sortBy: { + lastUpdated: 1 + }, + output: { + stdDevPopTotalSales: { + $stdDevPop: "$sales.totalSales", + window: { + documents: ["unbounded", "current"] + } + } + } + } +}, { + $project: { + company: 1, + name: 1, + "sales.totalSales": 1, + lastUpdated: 1, + stdDevPopTotalSales: 1 + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "sales": {}, + "company": "First Up Consultants", + "lastUpdated": { + "$date": "2025-06-11T10:48:01.291Z" + }, + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "stdDevPopTotalSales": null + } +] +``` diff --git a/api-reference/operators/accumulators/$stddevsamp.md b/api-reference/operators/accumulators/$stddevsamp.md new file mode 100644 index 0000000..308e6ba --- /dev/null +++ b/api-reference/operators/accumulators/$stddevsamp.md @@ -0,0 +1,172 @@ +--- +title: $stddevsamp +description: The $stddevsamp operator calculates the standard deviation of a specified sample of values and not the entire population +type: operators +category: accumulators +--- + +# $stddevsamp + +The `$stddevsamp` operator calculates the standard deviation by taking a specified sample of the values of a field. The standard deviation is calculated by taking a random sample of the specified size. If a precise standard deviation is needed, $stdDevPop must be used instead. + +## Syntax + +```javascript +{ + $stddevsamp: {fieldName} +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`fieldName`** | The field whose values are used to calculate the standard deviation of the specified sample size| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the standard deviation of total sales + +This query calculates the standard deviation of total sales across stores in the "Fourth Coffee" company by taking a random sample of 10 documents matching the filtering criteria. + +```javascript +db.stores.aggregate([{ + $match: { + "company": "Fourth Coffee" + } +}, { + $sample: { + size: 10 + } +}, { + $group: { + _id: "$company", + stdDev: { + $stdDevSamp: "$sales.totalSales" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "Fourth Coffee", + "stdDev": 22040.044055209048 + } +] +``` diff --git a/api-reference/operators/accumulators/$sum.md b/api-reference/operators/accumulators/$sum.md new file mode 100644 index 0000000..e8dfc39 --- /dev/null +++ b/api-reference/operators/accumulators/$sum.md @@ -0,0 +1,316 @@ +--- +title: $sum +description: The $sum operator calculates the sum of the values of a field based on a filtering criteria +type: operators +category: accumulators +--- + +# $sum + +The `$sum` operator calculates the sum of numeric values of a field or expression that match a filtering criteria. + +## Syntax + +```javascript +{ + $sum: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The field or expression to calculate the sum of. This can be a field, a numeric value, or an expression. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Using `$sum` in `$group` + +To compute total discount percentage per category across all promotion events in 2023: + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $unwind: "$promotionEvents.discounts" + }, + { + $match: { + "promotionEvents.promotionalDates.startDate.Year": 2023 + } + }, + { + $group: { + _id: "$promotionEvents.discounts.categoryName", + totalDiscountIn2023: { + $sum: "$promotionEvents.discounts.discountPercentage" + } + } + }, + { + $project: { + _id: 0, + categoryName: "$_id", + totalDiscountIn2023: 1 + } + } +]) +``` + +This query returns the following results: + +```json +[ + { + "categoryName": "Glass Frames", + "totalDiscountIn2023": 25 + }, + { + "categoryName": "Picture Hanging Supplies", + "totalDiscountIn2023": 14 + } +] +``` + +### Example 2: Using `$sum` in `$bucket` + +To get the total sales within defined sales boundaries: + +```javascript +db.stores.aggregate([{ + $bucket: { + groupBy: "$sales.totalSales", // Field to group by + boundaries: [0, 10000, 20000, 50000, 100000], // Sales ranges + default: "Other", // Default bucket for values outside the defined ranges + output: { + totalSalesSum: { + $sum: "$sales.totalSales" + }, // Sum the sales for each bucket + count: { + $sum: 1 + } // Count the number of documents in each bucket + } + } +}]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "Other", + "totalSalesSum": 454981695, + "count": 3001 + }, + { + "_id": 0, + "totalSalesSum": 20033725, + "count": 3903 + }, + { + "_id": 10000, + "totalSalesSum": 71303703, + "count": 4712 + }, + { + "_id": 50000, + "totalSalesSum": 756168541, + "count": 11025 + }, + { + "_id": 20000, + "totalSalesSum": 678976078, + "count": 18861 + } +] +``` + +### Example 3: Using `$sum` in `$setWindowFields` + +To calculate the total discount per sales category for promotions in 2023: + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $unwind: "$promotionEvents.discounts" + }, + { + $match: { + "promotionEvents.promotionalDates.startDate.Year": 2023 + } + }, + { + $setWindowFields: { + partitionBy: "$promotionEvents.discounts.categoryName", // Group by categoryName + output: { + totalDiscountIn2023: { + $sum: "$promotionEvents.discounts.discountPercentage", // Sum discount percentage + window: { + documents: ["unbounded", "unbounded"] // Aggregate over all documents in the partition + } + } + } + } + }, + { + $project: { + _id: 0, + categoryName: "$promotionEvents.discounts.categoryName", + discountPercentage: "$promotionEvents.discounts.discountPercentage", + totalDiscountIn2023: 1 + } + }, + { + $limit: 5 + } +]) +``` + +This query returns the following results: + +```json +[ + { + "totalDiscountIn2023": 1106, + "categoryName": "2-in-1 Laptops", + "discountPercentage": 25 + }, + { + "totalDiscountIn2023": 1106, + "categoryName": "2-in-1 Laptops", + "discountPercentage": 22 + }, + { + "totalDiscountIn2023": 1106, + "categoryName": "2-in-1 Laptops", + "discountPercentage": 19 + }, + { + "totalDiscountIn2023": 1106, + "categoryName": "2-in-1 Laptops", + "discountPercentage": 17 + }, + { + "totalDiscountIn2023": 1106, + "categoryName": "2-in-1 Laptops", + "discountPercentage": 10 + } +] +``` diff --git a/api-reference/operators/accumulators/$top.md b/api-reference/operators/accumulators/$top.md new file mode 100644 index 0000000..9e342ff --- /dev/null +++ b/api-reference/operators/accumulators/$top.md @@ -0,0 +1,288 @@ +--- +title: $top +description: The $top operator returns the first document from the result set sorted by one or more fields +type: operators +category: accumulators +--- + +# $top + +The `$top` operator sorts documents on one or more fields specified by the query and returns the first document matching the filtering criteria. It combines sorting and selection in a single operation, making it efficient for finding the highest or lowest values without requiring a separate sort stage. + +## Syntax + +```javascript +{ + $top: { + output: [listOfFields], + sortBy: { + < fieldName >: < sortOrder > + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`listOfFields`** | The list of fields to be returned for the last document in the result set| +| **`fieldName`** | The field to use for sorting the result set| +| **`sortOrder`** | 1 or -1. 1 implies sorting in ascending order of the value of the field while -1 implies sorting in descending order of the values of the field| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Get the top selling category per store + +To find the highest-selling category within the First Up Consultants company, run a query to retrieve stores within the company, sort the documents in descending order of total sales within each category and return the top document in the sorted result set. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $group: { + _id: "$company", + topSales: { + $top: { + output: ["$company", "$sales"], + sortBy: { + "sales.totalSales": -1 + } + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "First Up Consultants", + "topSales": [ + "First Up Consultants", + { + "salesByCategory": [ + { + "categoryName": "Towel Sets", + "totalSales": 520 + }, + { + "categoryName": "Bath Accessories", + "totalSales": 41710 + }, + { + "categoryName": "Drapes", + "totalSales": 42893 + }, + { + "categoryName": "Towel Racks", + "totalSales": 30773 + }, + { + "categoryName": "Hybrid Mattresses", + "totalSales": 39491 + }, + { + "categoryName": "Innerspring Mattresses", + "totalSales": 6410 + }, + { + "categoryName": "Bed Frames", + "totalSales": 41917 + }, + { + "categoryName": "Mattress Protectors", + "totalSales": 44124 + }, + { + "categoryName": "Bath Towels", + "totalSales": 5671 + }, + { + "categoryName": "Turkish Towels", + "totalSales": 25674 + } + ], + "revenue": 279183 + } + ] + } +] +``` + +### Example 2: Get the highest discount by promotion category + +To fetch the highest discount per sales category, first run a query to group all documents by store, then sort the documents in descending order of discount percentages within each promotion event and return the top document from the sorted result set per store. + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $unwind: "$promotionEvents.discounts" + }, + { + $group: { + _id: "$_id", + storeName: { + $first: "$name" + }, + highestDiscount: { + $top: { + sortBy: { + "promotionEvents.discounts.discountPercentage": -1 + }, + output: { + categoryName: "$promotionEvents.discounts.categoryName", + discountPercentage: "$promotionEvents.discounts.discountPercentage", + eventName: "$promotionEvents.eventName" + } + } + } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "64ec6589-068a-44a6-be5b-9d37bb0a90f1", + "storeName": "First Up Consultants | Computer Gallery - West Cathrine", + "highestDiscount": { + "categoryName": "Gaming Accessories", + "discountPercentage": 24, + "eventName": "Crazy Markdown Madness" + } + }, + { + "_id": "a58d0356-493b-44e6-afab-260aa3296930", + "storeName": "Fabrikam, Inc. | Outdoor Furniture Nook - West Lexie", + "highestDiscount": { + "categoryName": "Fire Pits", + "discountPercentage": 22, + "eventName": "Savings Showdown" + } + } +] +``` diff --git a/api-reference/operators/accumulators/$topn.md b/api-reference/operators/accumulators/$topn.md new file mode 100644 index 0000000..daa5d07 --- /dev/null +++ b/api-reference/operators/accumulators/$topn.md @@ -0,0 +1,327 @@ +--- +title: $topN +description: The $topN operator returns the first N documents from the result sorted by one or more fields +type: operators +category: accumulators +--- + +# $topN + +The `$topN` operator sorts documents on one or more fields specified by the query and returns the first N documents matching the filtering criteria. It extends the functionality of `$top` by allowing you to retrieve multiple top elements instead of just the single highest-ranked item. + +## Syntax + +```javascript +{ + $topN: { + output: [listOfFields], + sortBy: { + : < sortOrder > + }, + n: < numDocumentsToReturn > + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`listOfFields`** | The list of fields to be returned for the last document in the result set| +| **`fieldName`** | The field to use for sorting the result set| +| **`sortOrder`** | 1 or -1. 1 implies sorting in ascending order of the value of the field while -1 implies sorting in descending order of the values of the field| +| **`n`** | The number of documents to return from the top of the sorted result set | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Get the two stores with the lowest total sales + +To get the two lowest stores by sales within the First Up Consultants company, run a query to filter on the company name, sort the resulting documents in ascending order of sales and return the top two documents from the sorted result set. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $group: { + _id: "$company", + topSales: { + $topN: { + output: ["$company", "$sales"], + sortBy: { + "sales.totalSales": 1 + }, + n: 2 + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "First Up Consultants", + "topSales": [ + [ + "First Up Consultants", + { + "salesByCategory": [ + { + "categoryName": "Towel Sets", + "totalSales": 520 + }, + { + "categoryName": "Bath Accessories", + "totalSales": 41710 + }, + { + "categoryName": "Drapes", + "totalSales": 42893 + }, + { + "categoryName": "Towel Racks", + "totalSales": 30773 + }, + { + "categoryName": "Hybrid Mattresses", + "totalSales": 39491 + }, + { + "categoryName": "Innerspring Mattresses", + "totalSales": 6410 + }, + { + "categoryName": "Bed Frames", + "totalSales": 41917 + }, + { + "categoryName": "Mattress Protectors", + "totalSales": 44124 + }, + { + "categoryName": "Bath Towels", + "totalSales": 5671 + }, + { + "categoryName": "Turkish Towels", + "totalSales": 25674 + } + ], + "revenue": 279183 + } + ], + [ + "First Up Consultants", + { + "salesByCategory": [ + { + "categoryName": "Lavalier Microphones", + "totalSales": 40000 + }, + { + "categoryName": "Wireless Microphones", + "totalSales": 39691 + } + ], + "minimumSalesTarget": 30000, + "revenue": 50000 + } + ] + ] + } +] +``` + +### Example 2: Get the two most recent promotion events + +To find the two most recent promotion events for each store, group the documents in collection by store, sort them in ascending order of promotion dates and return the top two results from the sorted result set per store. + +```javascript +db.stores.aggregate([{ + $unwind: "$promotionEvents" + }, + { + $group: { + _id: "$_id", + storeName: { + $first: "$name" + }, + top2RecentPromotions: { + $topN: { + n: 2, + sortBy: { + "promotionEvents.promotionalDates.startDate.Year": -1, + "promotionEvents.promotionalDates.startDate.Month": -1, + "promotionEvents.promotionalDates.startDate.Day": -1 + }, + output: { + eventName: "$promotionEvents.eventName", + startDate: "$promotionEvents.promotionalDates.startDate" + } + } + } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "4a99546f-a1d2-4e61-ae9f-b8c7c1faf73c'", + "storeName": "Lakeshore Retail | Stationery Nook - West Van", + "top2RecentPromotions": [ + { + "eventName": "Crazy Markdown Madness", + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + } + }, + { + "eventName": "Flash Sale Fiesta", + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + } + } + ] + }, + { + "_id": "e0c47a06-4fe0-46b7-a309-8971bbb3978f", + "storeName": "VanArsdel, Ltd. | Baby Products Bargains - Elainamouth", + "top2RecentPromotions": [ + { + "eventName": "Crazy Deal Days", + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + } + } + ] + } +] +``` diff --git a/api-reference/operators/aggregation/$addfields.md b/api-reference/operators/aggregation/$addfields.md new file mode 100644 index 0000000..3332cc9 --- /dev/null +++ b/api-reference/operators/aggregation/$addfields.md @@ -0,0 +1,240 @@ +--- +title: $addFields +description: The $addFields stage in the aggregation pipeline is used to add new fields to documents. +type: operators +category: aggregation +--- + +# $addFields + +The $addFields stage in the aggregation pipeline is used to add new fields to documents. It can also be used to reset the values of existing fields. This stage is particularly useful when you need to create new fields based on existing data or modify existing fields within your documents. + +## Syntax + +```javascript +{ + $addFields: { + : , + : , + ... + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`newField1`** | The name of the new field to add or the existing field to modify. | +| **`expression1`** | The expression to compute the value of newField1. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Adding a new field + +This query adds a new field totalDiscountEvents that counts the number of promotion events + +```javascript +db.stores.aggregate([ + { + $addFields: { + totalDiscountEvents: { $size: "$store.promotionEvents" } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "promotionEvents": ["Summer Sale", "Black Friday", "Holiday Deals"] + }, + "totalDiscountEvents": 3 + } +] +``` + +### Example 2: Modifying an Existing Field + +This query adds a field totalStaffCount that sums up the full-time and part-time staff. + +```javascript +db.stores.aggregate([ + { + $addFields: { + totalStaffCount: { + $add: ["$store.staff.totalStaff.fullTime", "$store.staff.totalStaff.partTime"] + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "staff": { + "totalStaff": { + "fullTime": 12, + "partTime": 8 + } + } + }, + "totalStaffCount": 20 + } +] +``` + +### Example 3: Adding Nested Fields + +This query adds a nested field location.coordinates that combines latitude and longitude into an array. + +```javascript +db.stores.aggregate([ + { + $addFields: { + "store.location.coordinates": ["$store.location.lat", "$store.location.lon"] + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "location": { + "lat": 47.6097, + "lon": -122.3331, + "coordinates": [47.6097, -122.3331] + } + } + } +] +``` diff --git a/api-reference/operators/aggregation/$bucket.md b/api-reference/operators/aggregation/$bucket.md new file mode 100644 index 0000000..4e450d7 --- /dev/null +++ b/api-reference/operators/aggregation/$bucket.md @@ -0,0 +1,178 @@ +--- +title: $bucket +description: The $bucket operator groups input documents into buckets based on specified boundaries. +type: operators +category: aggregation +--- + +# $bucket + +The `$bucket` stage in an aggregation pipeline groups input documents into buckets based on specified boundaries. This is especially useful for creating histograms or categorizing data into ranges. It allows you to define custom bucket boundaries and provides a way to summarize data within these ranges. + +## Syntax + +```javascript +{ + $bucket: { + groupBy: , + boundaries: [ , , ... ], + default: , + output: { + : { }, + ... + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`groupBy`** | The expression to group documents by. | +| **`boundaries`** | An array of boundary values to define the buckets. The array must be sorted in ascending order and include at least two values. | +| **`default`** | The name of the bucket for documents that do not fall within the specified boundaries. | +| **`output`** | An optional field to specify computed fields for each bucket. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Categorizing `fullSales` into ranges + +This query categorizes the `fullSales` field into three buckets: `[0, 1000)`, `[1000, 5000)`, and `[5000, 10000)`. Documents that do not fall into these ranges are grouped into a default bucket. + +```javascript +db.stores.aggregate([ + { + $bucket: { + groupBy: "$sales.fullSales", + boundaries: [0, 1000, 5000, 10000], + default: "Other", + output: { + count: { $sum: 1 }, + totalSales: { $sum: "$sales.fullSales" } + } + } + } +]) +``` + +This query returns the following results: + +```json +[ + { "_id": 1000, "count": 1, "totalSales": 3700 }, + { "_id": "Other", "count": 41504, "totalSales": 0 } +] +``` diff --git a/api-reference/operators/aggregation/$changestream.md b/api-reference/operators/aggregation/$changestream.md new file mode 100644 index 0000000..ba10015 --- /dev/null +++ b/api-reference/operators/aggregation/$changestream.md @@ -0,0 +1,191 @@ +--- +title: $changeStream +description: The $changeStream stage opens a change stream cursor to track data changes in real-time. +type: operators +category: aggregation +--- + +# $changeStream + +The `$changeStream` aggregation stage opens a change stream cursor that tracks data changes in real-time. This stage enables applications to react to insert, update, delete, and other operations as they occur in the collection. + +## Syntax + +```javascript +{ + $changeStream: { + allChangesForCluster: , + fullDocument: , + fullDocumentBeforeChange: , + resumeAfter: , + startAfter: , + startAtOperationTime: , + showExpandedEvents: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`allChangesForCluster`** | Optional. Boolean. If true, returns changes for the entire cluster. Default is false. | +| **`fullDocument`** | Optional. String. Determines what to return for update operations. Options: 'default', 'updateLookup', 'whenAvailable', 'required'. | +| **`fullDocumentBeforeChange`** | Optional. String. Returns the preimage of the document. Options: "off", "whenAvailable", "required". | +| **`resumeAfter`** | Optional. Resume token to resume change stream after a specific event. | +| **`startAfter`** | Optional. Resume token to start change stream after a specific event. | +| **`startAtOperationTime`** | Optional. timestamp for starting change stream from a specific time. | +| **`showExpandedEvents`** | Optional. Boolean. Include another change stream events. Default is false. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Monitor all changes in stores collection + +This operation sets up a change stream to monitor all changes in the stores collection. + +```javascript +db.stores.aggregate([ + { + $changeStream: { + fullDocument: "updateLookup" + } + } +]) +``` + +When a store document is updated, the change stream returns the change event with the full document. + +```json +{ + "_id": { "_data": "AeARBpQ/AAAA" }, + "operationType": "update", + "fullDocument": { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "sales": { + "revenue": 42500 + }, + "company": "Trey Research", + "lastUpdated": "ISODate('2024-06-16T10:30:00.000Z')" + }, + "ns": { + "db": "StoreData", + "coll": "stores" + }, + "documentKey": { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac" + } +} +``` diff --git a/api-reference/operators/aggregation/$collstats.md b/api-reference/operators/aggregation/$collstats.md new file mode 100644 index 0000000..8920caa --- /dev/null +++ b/api-reference/operators/aggregation/$collstats.md @@ -0,0 +1,166 @@ +--- +title: $collStats +description: The $collStats stage in the aggregation pipeline is used to return statistics about a collection. +type: operators +category: aggregation +--- + +# $collStats + +The $collStats stage in the aggregation pipeline is used to return statistics about a collection. This stage can be particularly useful for understanding the performance characteristics of a collection, such as the number of documents, the size of the collection, and storage statistics. It provides detailed information that can help with database optimization and monitoring. + +## Syntax + +```javascript +{ + $collStats: { + latencyStats: { histograms: }, + storageStats: { scale: }, + count: {} + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`latencyStats`** | Optional. Specifies whether to include latency statistics. The `histograms` field is a boolean that indicates whether to include histograms of latency data. | +| **`storageStats`** | Optional. Specifies whether to include storage statistics. The `scale` field is a number that indicates the scale factor for the storage statistics. | +| **`count`** | Optional. Includes the count of documents in the collection. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example: Basic collection statistics + +This query counts all the documents in the stores collection. + +```javascript +db.stores.aggregate([ + { + $collStats: { + count: {} + } + } +]) +``` + +This query returns the following result: + +```json +[ + { "ns": "StoreData.stores", "count": 41505 } +] +``` diff --git a/api-reference/operators/aggregation/$convert.md b/api-reference/operators/aggregation/$convert.md new file mode 100644 index 0000000..7ff044f --- /dev/null +++ b/api-reference/operators/aggregation/$convert.md @@ -0,0 +1,250 @@ +--- +title: $convert +description: The $convert operator converts an expression into the specified type +type: operators +category: aggregation +--- + +# $convert + +The $convert operator converts an expression into a value of the specified type. + +## Syntax + +```javascript +{ + $convert: { + input: < expression > , + to: < type > , + format: < binData format > , + onError: < value to return on error > , + onNull: < value to return on null > + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The input value to be converted to the specified type| +| **`to`** | The type to convert the input value into| +| **`format`** | (Optional) The binData format of the input or output when converting a value to or from binData| +| **`onError`** | (Optional) The value to return when the conversion of the input to the specified type fails| +| **`onNull`** | (Optional) The value to return when the input value to be converted to the specified type is null or missing| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert an Int value into a String + +To convert the fullTime field from an integer to a string, run a query using the $convert operator to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + fulltimeStaff: "$staff.totalStaff.fullTime", + fulltimeStaffAsString: { + $convert: { + input: "$staff.totalStaff.fullTime", + to: "string" + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "fulltimeStaff": 3, + "fulltimeStaffAsString": "3" + } +] +``` + +### Example 2: Convert an Int value into a Boolean value + +To convert the fullTime field from an integer to a boolean, run a query using the $convert operator to make the conversion. Any positive value for the fullTime field will be converted to true. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + fulltimeStaff: "$staff.totalStaff.fullTime", + fulltimeStaffAsBool: { + $convert: { + input: "$staff.totalStaff.fullTime", + to: "bool" + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "fulltimeStaff": 3, + "fulltimeStaffAsBool": true + } +] +``` + +### Example 3: Convert an Int value into a Decimal value + +To convert the fullTime staff field from an integer to a decimal value, run a query using the $convert operator to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + fulltimeStaff: "$staff.totalStaff.fullTime", + fulltimeStaffAsDecimal: { + $convert: { + input: "$staff.totalStaff.fullTime", + to: "decimal" + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "fulltimeStaff": 3, + "fulltimeStaffAsDecimal": "Decimal128('3')" + } +] +``` diff --git a/api-reference/operators/aggregation/$densify.md b/api-reference/operators/aggregation/$densify.md new file mode 100644 index 0000000..5481d46 --- /dev/null +++ b/api-reference/operators/aggregation/$densify.md @@ -0,0 +1,249 @@ +--- +title: $densify +description: The $densify operator adds missing data points in a sequence of values within an array or collection. +type: operators +category: aggregation +--- + +# $densify + +The `$densify` stage in an aggregation pipeline is used to fill in missing data points within a sequence of values. It helps in creating a more complete dataset by generating missing values based on a specified field, range, and step. This is useful in scenarios like time-series data analysis, where gaps in data points need to be filled to ensure accurate analysis. + +## Syntax + +```javascript +{ + $densify: { + field: , + range: { + step: , + unit: , // Optional, e.g., "hour", "day", "month", etc. + bounds: [, ] // Optional + }, + partitionByFields: [, , ...] // Optional + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field on which densification is performed. | +| **`range.step`** | The step size for generating missing values. | +| **`range.unit`** | (Optional) The unit of the step size, such as time units (e.g., "hour", "day"). | +| **`range.bounds`** | (Optional) Specifies the range (lower and upper bounds) for densification. | +| **`partitionByFields`** | (Optional) Fields used to group data for densification. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Densify a time-series dataset + +This query fills in missing days in the date field. + +```javascript +db.aggregate([ + { + $documents: [ + { date: new ISODate("2024-01-01"), value: 10 }, + { date: new ISODate("2024-01-03"), value: 15 } + ] + }, + { + $densify: { + field: "date", + range: { + step: 1, + unit: "day", + bounds: "full" + } + } + } + ]); +``` + +This query returns the following results: + +```json +[ + { + "date": "ISODate('2024-01-01T00:00:00.000Z')", + "value": 10 + }, + { + "date": "ISODate('2024-01-02T00:00:00.000Z')" + }, + { + "date": "ISODate('2024-01-03T00:00:00.000Z')", + "value": 15 + } +] + +``` + +### Example 2: Densify numeric data + +This query fills in missing numeric values in the `sales.fullSales` field: + +```javascript +db.aggregate([ + { + $documents: [ + { level: 1, score: 10 }, + { level: 3, score: 30 } + ] + }, + { + $densify: { + field: "level", + range: { + step: 1, + bounds: [1, 5] + } + } + } + ]); +``` + +This query returns the following results: + +```json +[ + { + "level": 1, + "score": 10 + }, + { + "level": 2 + }, + { + "level": 3, + "score": 30 + }, + { + "level": 4 + } +] +``` + +## Limitations + +The following table summarizes the key restrictions and behaviors associated with the $densify stage in aggregation pipelines: + +| Category| Condition / Behavior | +| --- | --- | +| Field Restrictions | - Errors if any document has a **date** value and `unit` is **not specified**.
- Errors if any document has a **numeric** value and `unit` is **specified**.
- Field name **starts with `$`**. Use `$project` to rename it.| +| partitionByFields | - Any field evaluates to a **non-string** value.
- Field name **starts with `$`**. | +| range.bounds | - **Lower bound** defines the start value, regardless of existing documents.
- **Lower bound is inclusive**.
- **Upper bound is exclusive**.
- `$densify` does **not filter out** documents outside the bounds. | diff --git a/api-reference/operators/aggregation/$documents.md b/api-reference/operators/aggregation/$documents.md new file mode 100644 index 0000000..0e56d42 --- /dev/null +++ b/api-reference/operators/aggregation/$documents.md @@ -0,0 +1,281 @@ +--- +title: $documents +description: The $documents stage creates a pipeline from a set of provided documents. +type: operators +category: aggregation +--- + +# $documents + +The `$documents` aggregation pipeline stage is used to create a pipeline from a set of provided documents. This stage is particularly useful when you want to process specific documents without querying a collection. + +## Syntax + +```javascript +{ + $documents: [ + , + , + ... + ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | A JSON object representing a document to include in the pipeline. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Create a pipeline from specific documents + +This query demonstrates how to use the `$documents` stage to process a set of predefined documents: + +```javascript +db.aggregate([{ + $documents: [{ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + name: "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + location: { + lat: 60.1441, + lon: -141.5012 + }, + sales: { + fullSales: 3700 + }, + tag: ["#ShopLocal", "#SeasonalSale"] + }, { + _id: "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + name: "Contoso, Ltd. | Office Supply Deals - South Shana", + location: { + lat: 40.7128, + lon: -74.0060 + }, + sales: { + fullSales: 5400 + }, + tag: ["#TechDeals", "#FreeShipping"] + }] +}, { + $project: { + _id: 1, + name: 1, + "location.lat": 1, + "location.lon": 1, + "sales.fullSales": 1, + tags: "$tag" + } +}]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "sales": { + "fullSales": 3700 + }, + "tags": [ + "#ShopLocal", + "#SeasonalSale" + ] + }, + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "name": "Contoso, Ltd. | Office Supply Deals - South Shana", + "location": { + "lat": 40.7128, + "lon": -74.006 + }, + "sales": { + "fullSales": 5400 + }, + "tags": [ + "#TechDeals", + "#FreeShipping" + ] + } +] +``` + +### Example 2: Combine `$documents` with other pipeline stages + +This query combines the $documents pipeline stage along with the $match and $sort pipeline stages. + +```javascript +db.aggregate([{ + $documents: [{ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + name: "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + location: { + lat: 60.1441, + lon: -141.5012 + }, + sales: { + fullSales: 3700 + }, + tag: ["#ShopLocal", "#SeasonalSale"] + }, { + _id: "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + name: "Contoso, Ltd. | Office Supply Deals - South Shana", + location: { + lat: 40.7128, + lon: -74.0060 + }, + sales: { + fullSales: 5400 + }, + tag: ["#TechDeals", "#FreeShipping"] + }] +}, { + $match: { + "sales.fullSales": { + $gt: 4000 + } + } +}, { + $sort: { + "sales.fullSales": -1 + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "name": "Contoso, Ltd. | Office Supply Deals - South Shana", + "location": { "lat": 40.7128, "lon": -74.006 }, + "sales": { "fullSales": 5400 }, + "tag": [ "#TechDeals", "#FreeShipping" ] + } +] +``` + +## Limitations + +- The $documents stage is only supported in database-level aggregation pipelines. +- It must be the first stage in the pipeline to function correctly. diff --git a/api-reference/operators/aggregation/$facet.md b/api-reference/operators/aggregation/$facet.md new file mode 100644 index 0000000..c184d37 --- /dev/null +++ b/api-reference/operators/aggregation/$facet.md @@ -0,0 +1,187 @@ +--- +title: $facet +description: The $facet allows for multiple parallel aggregations to be executed within a single pipeline stage. +type: operators +category: aggregation +--- + +# $facet + +The `$facet` stage aggregation pipelines allow for multiple parallel aggregations to be executed within a single pipeline stage. It's useful for performing multiple analyses on the same dataset in a single query. + +## Syntax + +```javascript +{ + "$facet": { + "outputField1": [ { "stage1": {} }, { "stage2": {} } ], + "outputField2": [ { "stage1": {} }, { "stage2": {} } ] + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`outputFieldN`**| The name of the output field.| +| **`stageN`**| The aggregation stage to be executed.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Faceted search on sales and promotions + +To perform simultaneous analyses on sales and promotions, for specified product categories. The `salesAnalysis` pipeline unwinds the `salesByCategory`, filters for certain categories, and groups them to sum `totalSales`. The promotion analysis pipeline unwinds promotional events and their discounts, filters for specific categories like `Laptops`, `Smartphones` etc., and groups them to calculate the average discount percentage. The input documents from `stores` collection are fetched from the database only once, at the beginning of this operation. + +```javascript +db.stores.aggregate([ + { + $facet: { + salesAnalysis: [ + { $unwind: "$sales.salesByCategory" }, + { $match: { "sales.salesByCategory.categoryName": { $in: ["Laptops", "Smartphones", "Cameras", "Watches"] } } }, + { $group: { _id: "$sales.salesByCategory.categoryName", totalSales: { $sum: "$sales.salesByCategory.totalSales" } } } + ], + promotionAnalysis: [ + { $unwind: "$promotionEvents" }, + { $unwind: "$promotionEvents.discounts" }, + { $match: { "promotionEvents.discounts.categoryName": { $in: ["Laptops", "Smartphones", "Cameras", "Watches"] } } }, + { $group: { _id: "$promotionEvents.discounts.categoryName", avgDiscount: { $avg: "$promotionEvents.discounts.discountPercentage" } } } + ] + } + } +]).pretty() +``` + +This query returns the following result: + +```json +[ + { + "salesAnalysis": [ + { "_id": "Smartphones", "totalSales": 440815 }, + { "_id": "Laptops", "totalSales": 679453 }, + { "_id": "Cameras", "totalSales": 481171 }, + { "_id": "Watches", "totalSales": 492299 } + ], + "promotionAnalysis": [ + { "_id": "Smartphones", "avgDiscount": 14.32 }, + { "_id": "Laptops", "avgDiscount": 14.780645161290323 }, + { "_id": "Cameras", "avgDiscount": 15.512195121951219 }, + { "_id": "Watches", "avgDiscount": 15.174418604651162 } + ] + } +] +``` diff --git a/api-reference/operators/aggregation/$fill.md b/api-reference/operators/aggregation/$fill.md new file mode 100644 index 0000000..74f42f8 --- /dev/null +++ b/api-reference/operators/aggregation/$fill.md @@ -0,0 +1,301 @@ +--- +title: $fill +description: The $fill stage allows filling missing values in documents based on specified methods and criteria. +type: operators +category: aggregation +--- + +# $fill + +The `$fill` stage is used to fill missing or null values in documents within the aggregation pipeline. It provides various methods to populate missing data, including using static values, linear interpolation, or values from previous/next documents. + +## Syntax + +```javascript +{ + $fill: { + sortBy: , + partitionBy: , + partitionByFields: , + output: { + : { value: }, + : { method: } + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`sortBy`** | Specifies the sort order for documents when applying fill methods that depend on document order. | +| **`partitionBy`** | Optional. Groups documents into partitions. Fill operations are applied within each partition separately. | +| **`partitionByFields`** | Optional. Alternative syntax for partitionBy using an array of field names. | +| **`output`** | Specifies the fields to fill and the method or value to use for filling missing data. | + +### Fill Methods + +| Method | Description | +| --- | --- | +| **`value`** | Fill with a specified static value or expression result. | +| **`linear`** | Fill using linear interpolation between known values (numeric fields only). | +| **`locf`** | Last Observation Carried Forward - use the last known value. | +| **`linear`** | Linear interpolation between surrounding values. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "location": { + "lat": 60.7954, + "lon": -142.0012 + }, + "staff": { + "totalStaff": { + "fullTime": 18, + "partTime": 17 + } + }, + "sales": { + "totalSales": 37701, + "salesByCategory": [ + { + "categoryName": "Mattress Toppers", + "totalSales": 37701 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Price Drop Palooza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Bath Accessories", + "discountPercentage": 18 + }, + { + "categoryName": "Pillow Top Mattresses", + "discountPercentage": 17 + } + ] + } + ] +} +``` + +### Example 1: Fill missing values with static value + +This query fills missing `totalSales` values in the `salesByCategory` array with a default value of 0. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $unwind: "$sales.salesByCategory" +}, { + $fill: { + output: { + "sales.salesByCategory.totalSales": { + value: 0 + } + } + } +}, { + $group: { + _id: "$_id", + name: { + $first: "$name" + }, + salesByCategory: { + $push: "$sales.salesByCategory" + } + } +}]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "affdc09c-7356-4fff-a857-e8301f57159c", + "name": "First Up Consultants | Sports Gear Pantry - Wildermanhaven", + "salesByCategory": [ + { + "categoryName": "Baseball Gear", + "totalSales": 33878 + }, + { + "categoryName": "Volleyball Gear", + "totalSales": 34031 + } + ] + }, + { + "_id": "1cf667b4-d8ce-4f1a-bad1-a1f0bbce26c2", + "name": "First Up Consultants | Picture Frame Variety - New Abrahamborough", + "salesByCategory": [ + { + "categoryName": "Picture Hanging Supplies", + "totalSales": 7229 + }, + { + "categoryName": "Collage Frames", + "totalSales": 40014 + } + ] + } +] +``` + +### Example 2: Fill missing staff data using last observation carried forward + +This query fills missing part-time staff data using the last known value within each store group. + +```javascript +db.stores.aggregate([{ + $fill: { + sortBy: { + "_id": 1 + }, + output: { + "staff.totalStaff.partTime": { + method: "locf" + } + } + } +}, { + $project: { + name: 1, + "staff.totalStaff": 1 + } +}]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "00003278-4226-4ca7-871d-e80d8f414431", + "name": "Wide World Importers | Camera Depot - Lake Luramouth", + "staff": { + "totalStaff": { + "fullTime": 20, + "partTime": 6 + } + } + }, + { + "_id": "00009bd0-c44e-4cc8-ab03-347076d74a1a", + "name": "Wide World Importers | Music Stop - Rebeccaside", + "staff": { + "totalStaff": { + "fullTime": 9, + "partTime": 0 + } + } + } +] +``` + +### Example 3: Fill missing discount percentages with average value + +This query fills missing discount percentages with the average discount percentage across all stores. + +```javascript +db.stores.aggregate([ + { $unwind: "$promotionEvents" }, + { $unwind: "$promotionEvents.discounts" }, + { + $fill: { + partitionBy: "$promotionEvents.eventName", + sortBy: { "promotionEvents.discounts.categoryName": 1 }, + output: { + "promotionEvents.discounts.discountPercentage": { + value: { $avg: "$promotionEvents.discounts.discountPercentage" } + } + } + } + }, + { + $group: { + _id: { storeId: "$_id", eventName: "$promotionEvents.eventName" }, + storeName: { $first: "$name" }, + eventName: { $first: "$promotionEvents.eventName" }, + discounts: { $push: "$promotionEvents.discounts" } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": { + "storeId": "70d4cc90-23b1-46e3-8f59-630648e311a4", + "eventName": "Price Slash Spectacular" + }, + "storeName": "Wide World Importers | Music Bazaar - West Johnpaulhaven", + "eventName": "Price Slash Spectacular", + "discounts": [ + { + "categoryName": "CDs", + "discountPercentage": 22 + }, + { + "categoryName": "Vinyl Records", + "discountPercentage": 21 + } + ] + }, + { + "_id": { + "storeId": "24873ac4-b2d1-4216-a425-3375a384b23d", + "eventName": "Massive Deal Mania" + }, + "storeName": "Northwind Traders | Furniture Pantry - Farrellchester", + "eventName": "Massive Deal Mania", + "discounts": [ + { + "categoryName": "Bookcases", + "discountPercentage": 22 + }, + { + "categoryName": "Cabinets", + "discountPercentage": 8 + } + ] + } +] +``` + +## Use Cases + +- **Data Cleaning**: Fill missing values in imported datasets +- **Time Series Data**: Handle gaps in sequential data using interpolation +- **Default Values**: Assign default values to optional fields +- **Data Normalization**: Ensure consistent data structure across documents diff --git a/api-reference/operators/aggregation/$geonear.md b/api-reference/operators/aggregation/$geonear.md new file mode 100644 index 0000000..4bb4c4d --- /dev/null +++ b/api-reference/operators/aggregation/$geonear.md @@ -0,0 +1,262 @@ +--- +title: $geoNear +description: The $geoNear operator finds and sorts documents by their proximity to a geospatial point, returning distance information for each document. +type: operators +category: aggregation +--- + +# $geoNear + +The `$geoNear` aggregation stage calculates distances between a specified point and the location field in each document, sorts the documents by distance, and can optionally limit results by distance. + +## Syntax + +```javascript +{ + $geoNear: { + near: { + type: "Point", + coordinates: [, ] + }, + distanceField: , + maxDistance: , + minDistance: , + query: , + includeLocs: , + distanceMultiplier: , + spherical: , + key: + } +} +``` + +## Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `near` | Object | The point from which to calculate distances | +| `distanceField` | String | The field that contains computed distance | +| `maxDistance` | Number | Optional. Maximum distance in meters from point | +| `minDistance` | Number | Optional. Minimum distance in meters from point | +| `query` | Document | Optional query conditions | +| `includeLocs` | Boolean | Optional. Include locations in results | +| `distanceMultiplier` | Number | Optional. Multiply distances by this value | +| `spherical` | Boolean | Must be true for 2dsphere indexes | +| `key` | String | Optional. Field path to use for calculating distances | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "location": { + "lat": 60.7954, + "lon": -142.0012 + }, + "staff": { + "totalStaff": { + "fullTime": 18, + "partTime": 17 + } + }, + "sales": { + "totalSales": 37701, + "salesByCategory": [ + { + "categoryName": "Mattress Toppers", + "totalSales": 37701 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Price Drop Palooza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Bath Accessories", + "discountPercentage": 18 + }, + { + "categoryName": "Pillow Top Mattresses", + "discountPercentage": 17 + } + ] + } + ] +} +``` + +### Example 1: Basic distance calculation + +This query retrieves all stores near the "VanArsdel Picture Frame Store" location, sorted by distance: + +```javascript +db.stores.aggregate([ + { + $geoNear: { + near: { + type: "Point", + coordinates: [-141.9922, 16.8331] // VanArsdel Picture Frame Store location + }, + distanceField: "distance", + spherical: true + } + }, + { + $project: { + name: 1, + distance: 1 + } + } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "643b2756-c22d-4063-9777-0945b9926346", + "name": "Contoso, Ltd. | Outdoor Furniture Corner - Pagacfort", + "distance": 5458613.2813355485 + }, + { + "_id": "daa71e60-75d4-4e03-8b45-9df59af0811f", + "name": "First Up Consultants | Handbag Corner - South Salvatore", + "distance": 5469362.958855379 + }, + { + "_id": "02a78a15-b1fc-4bbd-ae1d-641b7428dc78", + "name": "VanArsdel, Ltd. | Kitchen Appliance Corner - Llewellynberg", + "distance": 5472684.4628977 + } +] +``` + +### Example 2: With distance limits and optional query + +This query retrieves all stores within 30 KM of "Proseware Home Entertainment Hub" that have more than 10 full-time staff: + +```javascript +db.stores.aggregate([ + { + $geoNear: { + near: { + type: "Point", + coordinates: [69.7296, 70.1272] // "Proseware Home Entertainment Hub" location + }, + distanceField: "distance", + maxDistance: 30000, // 30 kilometers in meters + query: { "staff.totalStaff.fullTime": { $gt: 10 } }, + spherical: true + } + }, + { + $project: { + name: 1, + distance: 1, + "staff.totalStaff.fullTime": 1 + } + } +]) +``` + +The first result returned by this query is: + +```javascript +[ + { + "_id": "bbec6d3e-1666-45b4-8803-8b7ef8544845", + "name": "First Up Consultants | Baby Products Bargains - South Keenan", + "staff": { + "totalStaff": { + "fullTime": 19 + } + }, + "distance": 29934.71888123174 + } +] +``` + +### Example 3: Including location data and distance multiplier + +This query retrieves stores with distance in kilometers and included location data: + +```javascript +db.stores.aggregate([ + { + $geoNear: { + near: { + type: "Point", + coordinates: [-38.4071, -47.2548] // "Fabrikam Car Accessory Outlet" location + }, + distanceField: "distanceInKm", + includeLocs: "storeLocation", + distanceMultiplier: 0.001, // Convert meters to kilometers + spherical: true + } + }, + { + $project: { + name: 1, + distanceInKm: 1, + storeLocation: 1 + } + } +]) +``` + +The first three results returned by this query are: + +```javascript +[ + { + "_id": "b677846e-bb73-46ec-9cba-7d94afee382c", + "name": "Northwind Traders | Health Food Shoppe - Brooklynmouth", + "storeLocation": { + "lat": -38.3032, + "lon": -132.7866 + }, + "distanceInKm": 9.095634270192285 + }, + { + "_id": "27c64b44-2382-4477-b3ce-c08e74882156", + "name": "Relecloud | VR Headset Gallery - West Jonasbury", + "storeLocation": { + "lat": -37.9628, + "lon": -132.6637 + }, + "distanceInKm": 34.7104536140246 + }, + { + "_id": "505e83eb-09bc-46a4-ba85-16135611b9de", + "name": "Fabrikam, Inc. | Pharmacy Hub - Elijahville", + "storeLocation": { + "lat": -38.0349, + "lon": -47.9571 + }, + "distanceInKm": 82.92766541748313 + } +] +``` + +## Limitations + +* Can't use with sharded collections +* Only one $geoNear stage per pipeline +* Must be the first stage in the pipeline diff --git a/api-reference/operators/aggregation/$group.md b/api-reference/operators/aggregation/$group.md new file mode 100644 index 0000000..9da180c --- /dev/null +++ b/api-reference/operators/aggregation/$group.md @@ -0,0 +1,145 @@ +--- +title: $group +description: The $group stage groups documents by specified identifier expressions and applies accumulator expressions. +type: operators +category: aggregation +--- + +# $group + +The `$group` aggregation stage groups documents by specified identifier expressions and applies accumulator expressions to create computed fields for each group. This stage is essential for data aggregation and summarization operations. + +## Syntax + +```javascript +{ + $group: { + _id: , + : { : }, + : { : } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`_id`** | Required. The expression to group by. Use null to calculate accumulated values for all input documents. | +| **`field`** | Optional. Computed using accumulator operators like $sum, $avg, $max, $min, $count, etc. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "location": { + "lat": 60.7954, + "lon": -142.0012 + }, + "staff": { + "totalStaff": { + "fullTime": 18, + "partTime": 17 + } + }, + "sales": { + "totalSales": 37701, + "salesByCategory": [ + { + "categoryName": "Mattress Toppers", + "totalSales": 37701 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Price Drop Palooza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Bath Accessories", + "discountPercentage": 18 + }, + { + "categoryName": "Pillow Top Mattresses", + "discountPercentage": 17 + } + ] + } + ] +} +``` + +### Example 1: Group staffing analysis by city + +This query groups stores by city and analyzes the staffing patterns across different locations. + +```javascript +db.stores.aggregate([ + { + $group: { + _id: "$city", + totalFullTimeStaff: { $sum: "$staff.employeeCount.fullTime" }, + totalPartTimeStaff: { $sum: "$staff.employeeCount.partTime" }, + avgFullTimeStaff: { $avg: "$staff.employeeCount.fullTime" }, + storesInCity: { $count: {} } + } + }, + { + $project: { + city: "$_id", + totalFullTimeStaff: 1, + totalPartTimeStaff: 1, + avgFullTimeStaff: { $round: ["$avgFullTimeStaff", 1] }, + storesInCity: 1, + fullTimeRatio: { + $round: [ + { $divide: ["$totalFullTimeStaff", { $add: ["$totalFullTimeStaff", "$totalPartTimeStaff"] }] }, + 2 + ] + } + } + }, + { $limit : 2} +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "New Ellsworth", + "totalFullTimeStaff": 11, + "totalPartTimeStaff": 1, + "avgFullTimeStaff": 11, + "storesInCity": 1, + "city": "New Ellsworth", + "fullTimeRatio": 0.92 + }, + { + "_id": "Jalonborough", + "totalFullTimeStaff": 4, + "totalPartTimeStaff": 1, + "avgFullTimeStaff": 4, + "storesInCity": 1, + "city": "Jalonborough", + "fullTimeRatio": 0.8 + } +] +``` diff --git a/api-reference/operators/aggregation/$indexstats.md b/api-reference/operators/aggregation/$indexstats.md new file mode 100644 index 0000000..40cf1e9 --- /dev/null +++ b/api-reference/operators/aggregation/$indexstats.md @@ -0,0 +1,190 @@ +--- +title: $indexStats +description: The $indexStats stage returns usage statistics for each index in the collection. +type: operators +category: aggregation +--- + +# $indexStats + +The `$indexStats` aggregation stage returns usage statistics for each index in the collection. This stage is useful for analyzing index performance, identifying unused indexes, and optimizing query performance. + +## Syntax + +```javascript +{ + $indexStats: {} +} +``` + +## Parameters + +The `$indexStats` stage takes no parameters. + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Fetch index statistics + +This query retrieves usage statistics for all indexes on the stores collection. + +```javascript +db.stores.aggregate([ + { $indexStats: {} } +]) +``` + +The query returns statistics for each index including access patterns and usage frequency. + +```json +[ + { + "name": "_id_", + "key": { "_id": 1 }, + "accesses": { "ops": 41675, "since": "2025-06-07T13:51:41.231Z" }, + "spec": { "v": 2, "key": { "_id": 1 }, "name": "_id_" } + }, + { + "name": "location_2dsphere", + "key": { "location": "2dsphere" }, + "accesses": { "ops": 0, "since": "2025-06-07T13:51:41.231Z" }, + "spec": { + "v": 2, + "key": { "location": "2dsphere" }, + "name": "location_2dsphere", + "2dsphereIndexVersion": 3 + } + }, + { + "name": "name_text_sales.salesByCategory.categoryName_text_promotionEvents.eventName_text_promotionEvents.discounts.categoryName_text", + "key": { + "name": "text", + "sales.salesByCategory.categoryName": "text", + "promotionEvents.eventName": "text", + "promotionEvents.discounts.categoryName": "text" + }, + "accesses": { "ops": 8, "since": "2025-06-07T13:51:41.231Z" }, + "spec": { + "v": 2, + "key": { + "name": "text", + "sales.salesByCategory.categoryName": "text", + "promotionEvents.eventName": "text", + "promotionEvents.discounts.categoryName": "text" + }, + "name": "name_text_sales.salesByCategory.categoryName_text_promotionEvents.eventName_text_promotionEvents.discounts.categoryName_text" + } + } +] +``` diff --git a/api-reference/operators/aggregation/$isnumber.md b/api-reference/operators/aggregation/$isnumber.md new file mode 100644 index 0000000..794339f --- /dev/null +++ b/api-reference/operators/aggregation/$isnumber.md @@ -0,0 +1,229 @@ +--- +title: $isNumber +description: The $isNumber operator checks if a specified expression is a numerical type +type: operators +category: aggregation +--- + +# $isNumber + +The `$isNumber` operator returns true if the input expression is a numerical type. The `$isNumber` operator returns false for an expression of any other type. + +## Syntax + +```javascript +{ + $isNumber: < expression > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The specified value to check for a number| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Check if a Double value is a number + +To verify if the value of the latitude field is numeric, run a query using the $isNumber operator to validate that the double value of the field is a number. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeIsNumber: { + $isNumber: "$location.lat" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeIsNumber": true + } +] +``` + +### Example 2: Check if an Int value is a number + +To verify if the value of the totalSales field is numeric, run a query using the $isNumber operator to validate that the double value of the field is a number. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalTotalSales: "$sales.totalSales", + totalSalesIsNumber: { + $isNumber: "$sales.totalSales" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalTotalSales": 9366, + "totalSalesIsNumber": true + } +] +``` + +### Example 3: Check if a string is a number + +To verify if the value of the _id field is numeric, run a query using the $isNumber operator to validate that the string value of the field is not a number. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + idIsNumber: { + $isNumber: "$_id" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "idIsNumber": false + } +] +``` diff --git a/api-reference/operators/aggregation/$lookup.md b/api-reference/operators/aggregation/$lookup.md new file mode 100644 index 0000000..d711ca2 --- /dev/null +++ b/api-reference/operators/aggregation/$lookup.md @@ -0,0 +1,252 @@ +--- +title: $lookup +description: The $lookup stage in the Aggregation Framework is used to perform left outer joins with other collections. +type: operators +category: aggregation +--- + +# $lookup + +The `$lookup` stage in the Aggregation Framework is used to perform left outer joins with other collections. It allows you to combine documents from different collections based on a specified condition. This operator is useful for enriching documents with related data from other collections without having to perform multiple queries. + +## Syntax + +```javascript +{ + $lookup: { + from: , + localField: , + foreignField: , + as: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`from`** | The name of the collection to join with.| +| **`localField`** | The field from the input documents that are matched with the `foreignField`.| +| **`foreignField`** | The field from the documents in the `from` collection that are matched with the `localField`.| +| **`as`** | The name of the new array field to add to the input documents. This array contains the matched documents from the `from` collection.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +Let's say we have another `ratings` collection with two documents. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "rating": 5 +} +{ + "_id": "fecca713-35b6-44fb-898d-85232c62db2f", + "rating": 3 +} +``` + +### Example 1: Combine two collections to list promotion events for stores with a rating of 5 + +This query joins the `ratings` collection with the `stores` collection to list promotion events related to each store having a 5 rating. + +```javascript +db.ratings.aggregate([ + // filter based on rating in ratings collection + { + $match: { + "rating": 5 + } + }, + // find related documents in stores collection + { + $lookup: { + from: "stores", + localField: "_id", + foreignField: "_id", + as: "storeEvents" + } + }, + // deconstruct array to output a document for each element of the array + { + $unwind: "$storeEvents" + }, + // Include only _id and name fields in the output + { $project: { _id: 1, "storeEvents.name": 1 } } + +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "storeEvents": { "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile" } + } +] +``` + +### Example 2: Joining two collections (ratings and stores) using a variable from ratings. + +```javascript +db.ratings.aggregate([ + { + $match: { rating: 5 } + }, + { + $lookup: { + from: "stores", + let: { id: "$_id" }, + pipeline: [ + { + $match: { + $expr: { $eq: ["$_id", "$$id"] } + } + }, + { + $project: { _id: 0, name: 1 } + } + ], + as: "storeInfo" + } + }, + { + $unwind: "$storeInfo" + }, + { + $project: { + _id: 1, + rating: 1, + "storeInfo.name": 1 + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "rating": 5, + "storeInfo": { + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile" + } + } +] +``` diff --git a/api-reference/operators/aggregation/$match.md b/api-reference/operators/aggregation/$match.md new file mode 100644 index 0000000..c7162d8 --- /dev/null +++ b/api-reference/operators/aggregation/$match.md @@ -0,0 +1,227 @@ +--- +title: $match +description: The $match stage in the aggregation pipeline is used to filter documents that match a specified condition. +type: operators +category: aggregation +--- + +# $match + +The `$match` stage in the aggregation pipeline is used to filter documents that match a specified condition. It's similar to the `find` operation but is used within the aggregation pipeline to narrow down the documents that pass through to the next stage. This stage is highly useful for optimizing performance by reducing the number of documents that need to be processed in subsequent stages. + +## Syntax + +```javascript +{ + $match: { + + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| A standard MongoDB query document that specifies the conditions that the documents must meet.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Match documents using string comparison + +This query retrieves documents where the `_id` is "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5": + +```javascript +db.stores.aggregate([ + { + $match: { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "employeeCount": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + }, + { + "categoryName": "DJ Cables", + "totalSales": 1000 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [], + "tag": [ + "#ShopLocal", + "#NewArrival", + "#NewArrival", + "#FreeShipping" + ], + "company": "Lakeshore Retail", + "city": "Port Cecile", + "lastUpdated": "2025-08-04T05:57:04.619Z", + "storeOpeningDate": "2024-09-12T10:21:58.274Z" + } +] +``` + +### Example 2: Match documents using numeric comparison + +This query retrieves all stores where the total sales are greater than $35,000: + +```javascript +db.stores.aggregate([ + { + $match: { + "sales.totalSales": { $gt: 35000 } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 }, + // Include only _id and name fields in the output + { $project: { _id: 1, name: 1 } } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34", + "name": "Northwind Traders | Bed and Bath Place - West Oraland" + }, + { + "_id": "57cc4095-77d9-4345-af20-f8ead9ef0197", + "name": "Wide World Importers | Bed and Bath Store - West Vitafort" + }, + { + "_id": "560099f8-325f-4c35-a4e5-2e0879eb95af", + "name": "Wide World Importers | Bed and Bath Depot - North Maritzaberg" + } +] +``` + +### Example 3: Match documents within sub documents + +This query retrieves all stores with a discount of 15% on DJ Mixers: + +```javascript +db.stores.aggregate([ + { + $match: { + "promotionEvents.discounts": { + $elemMatch: { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 }, + // Include only _id and name fields in the output + { $project: { _id: 1, name: 1 } } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile" + }, + { + "_id": "3c7eda41-23a1-4226-abf6-17ee9e851b5b", + "name": "Boulder Innovations | DJ Equipment Bazaar - New Ceasarview" + }, + { + "_id": "63831a7d-13a9-4d8b-bf1d-ac004057f96d", + "name": "Contoso, Ltd. | DJ Equipment Shop - Reillyfurt" + } +] +``` diff --git a/api-reference/operators/aggregation/$merge.md b/api-reference/operators/aggregation/$merge.md new file mode 100644 index 0000000..ad631e1 --- /dev/null +++ b/api-reference/operators/aggregation/$merge.md @@ -0,0 +1,143 @@ +--- +title: $merge +description: The $merge stage in an aggregation pipeline writes the results of the aggregation to a specified collection. +type: operators +category: aggregation +--- + +# $merge + +The `$merge` stage in an aggregation pipeline is used to write the results of the aggregation query into a specified collection. This stage is particularly useful for tasks like updating or inserting documents into a target collection based on the output of an aggregation operation. It helps streamline workflows by combining data transformation and data persistence in a single operation. + +## Syntax + +```javascript +{ + $merge: { + into: , + on: , + whenMatched: , + whenNotMatched: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`into`** | Specifies the target collection where the aggregation results will be written. | +| **`on`** | Specifies the field(s) to identify matching documents in the target collection. | +| **`whenMatched`** | Specifies the action to take when a matching document is found. Options include `merge`, `replace`, `keepExisting`, `fail`, or a custom pipeline. | +| **`whenNotMatched`** | Specifies the action to take when no matching document is found. Options include `insert` or `discard`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Merge data into a collection + +This query aggregates documents and writes the results to a collection named `salesSummary`, updating existing documents where the `_id` matches and inserting new documents otherwise. + +```javascript +db.sales.aggregate([ + { + $group: { + _id: "$sales.salesByCategory.categoryName", + totalSales: { $sum: "$sales.salesByCategory.totalSales" } + } + }, + { + $merge: { + into: "salesSummary", + on: "_id", + whenMatched: "merge", + whenNotMatched: "insert" + } + } +]) +``` + +### Example 2: Replace documents in the target collection + +This example replaces documents in the `promotionEventsSummary` collection based on the `_id` field. + +```javascript +db.promotionEvents.aggregate([ + { + $project: { + _id: "$eventName", + startDate: "$promotionalDates.startDate", + endDate: "$promotionalDates.endDate", + totalDiscounts: { $size: "$discounts" } + } + }, + { + $merge: { + into: "promotionEventsSummary", + on: "_id", + whenMatched: "replace", + whenNotMatched: "insert" + } + } +]) +``` diff --git a/api-reference/operators/aggregation/$out.md b/api-reference/operators/aggregation/$out.md new file mode 100644 index 0000000..f2975bc --- /dev/null +++ b/api-reference/operators/aggregation/$out.md @@ -0,0 +1,175 @@ +--- +title: $out +description: The `$out` stage in an aggregation pipeline writes the resulting documents to a specified collection. +type: operators +category: aggregation +--- + +# $out + +The `$out` stage in an aggregation pipeline allows you to write the resulting documents of the pipeline into a specified collection. It is commonly used to save the output of complex aggregation operations for further use or analysis. When used, the specified collection is either created or replaced with the new documents. + +## Syntax + +```javascript +{ + $out: "" +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The name of the collection where the aggregation result will be stored. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1:Writing aggregation results to a new collection + +This query writes stores with total sales greater than 30,000 into a new collection called `highSales`. + +```javascript +db.stores.aggregate([ + { + $match: { + "sales.salesByCategory.totalSales": { $gt: 30000 } + } + }, + { + $out: "highSales" + } +]) +``` + +### Example 2: Writing processed data to another collection + +This query extracts promotion events and writes them into a collection named `promotionEventsSummary`. + +```javascript +db.stores.aggregate([ + { + $project: { + eventName: 1, + promotionalDates: 1, + "discounts.categoryName": 1, + "discounts.discountPercentage": 1 + } + }, + { + $out: "promotionEventsSummary" + } +]) +``` diff --git a/api-reference/operators/aggregation/$redact.md b/api-reference/operators/aggregation/$redact.md new file mode 100644 index 0000000..c54de97 --- /dev/null +++ b/api-reference/operators/aggregation/$redact.md @@ -0,0 +1,239 @@ +--- +title: $redact +description: The $redact operator filters the content of the documents based on access rights. +type: operators +category: aggregation +--- + +# $redact + +The `$redact` stage in aggregation pipeline is used to filter fields of the documents in a collection dynamically based on access rights or other conditions. It processes each document in the pipeline and removes or retains fields based on the specified logic. + +## Syntax + +```javascript +{ + $redact: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | A valid MongoDB expression that evaluates to one of the following: `$$DESCEND`, `$$PRUNE`, or `$$KEEP`. These variables determine whether to keep, remove, or traverse deeper into the document. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Redacting sensitive information + +This query filters the `promotionEvents` field for documents where the `discountPercentage` in a promotion exceeds 15%. + +```javascript +db.stores.aggregate([ + { + $redact: { + $cond: { + if: { + $gt: ["$promotionEvents.discounts.discountPercentage", 15] + }, + then: "$$PRUNE", + else: "$$DESCEND" + } + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "new-store-001", + "name": "Adatum Corporation - Downtown Branch", + "sales": { + "totalSales": 5000 + }, + "createdDate": "2025-06-11T11:11:32.262Z", + "status": "new", + "staff": { + "totalStaff": { + "fullTime": 0, + "partTime": 0 + } + }, + "version": 1, + "storeOpeningDate": "2025-06-11T11:11:32.262Z", + "storeFeatures": 213 + }, + { + "_id": "gaming-store-mall-001", + "name": "Trey Research | Gaming Paradise - Mall Location", + "location": { + "lat": 35.6762, + "lon": 139.6503 + }, + "createdDate": "2025-06-11T11:13:27.180Z", + "status": "active", + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 12 + }, + "manager": "Alex Johnson", + "departments": [ + "gaming", + "accessories", + "repairs" + ] + }, + "sales": { + "totalSales": 0, + "salesByCategory": [] + }, + "operatingHours": { + "weekdays": "10:00-22:00", + "weekends": "09:00-23:00" + }, + "metadata": { + "version": 1, + "source": "store-management-system" + }, + "storeOpeningDate": "2025-06-11T11:11:32.262Z", + "storeFeatures": 189 + } +] +``` + +### Example 2: Restricting access based on tags + +This query removes all documents that contain the tag `#MembershipDeals`. + +```javascript +db.stores.aggregate([ + { + $redact: { + $cond: { + if: { + $in: ["#MembershipDeals", "$tag"] + }, + then: "$$PRUNE", + else: "$$DESCEND" + } + } + } +]) +``` diff --git a/api-reference/operators/aggregation/$replacewith.md b/api-reference/operators/aggregation/$replacewith.md new file mode 100644 index 0000000..52e214c --- /dev/null +++ b/api-reference/operators/aggregation/$replacewith.md @@ -0,0 +1,198 @@ +--- +title: $replaceWith +description: The $replaceWith operator in DocumentDB returns a document after replacing a document with the specified document +type: operators +category: aggregation +--- + +# $replaceWith + +The `$replaceWith` aggregation stage operator is used to replace the input document with the specified document. The `$replaceWith` operator transforms documents from one structure to another or replaces them entirely with new fields and values. + +## Syntax + +```javascript +{ + "$replaceWith": +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`newDocument`** | The new document to replace the original document| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Return a document that replaces the contents of the original document with a subset of items + +First, match a specific document to replace by the _id field and replace the contents of the document with the specified fields. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "bda56164-954d-4f47-a230-ecf64b317b43" + } +}, { + $replaceWith: { + _id: "$_id", + name: "$name", + sales: "$sales.totalSales" + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "bda56164-954d-4f47-a230-ecf64b317b43", + "name": "Boulder Innovations | Home Security Place - Ankundingburgh", + "sales": 37015 + } +] +``` + +### Example 2 - Return a document that replaces the contents of the original document after aggregating specified fields + +```javascript +db.stores.aggregate([{ + $match: { + _id: "bda56164-954d-4f47-a230-ecf64b317b43" + } +}, { + $replaceWith: { + _id: "$_id", + name: "$name", + totalStaff: { + $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + } + } +}]) +``` + +This returns the following result: + +```json +[ + { + "_id": "bda56164-954d-4f47-a230-ecf64b317b43", + "name": "Boulder Innovations | Home Security Place - Ankundingburgh", + "totalStaff": 29 + } +] +``` diff --git a/api-reference/operators/aggregation/$sample.md b/api-reference/operators/aggregation/$sample.md new file mode 100644 index 0000000..3552ac1 --- /dev/null +++ b/api-reference/operators/aggregation/$sample.md @@ -0,0 +1,164 @@ +--- +title: $sample +description: The $sample operator in DocumentDB returns a randomly selected number of documents +type: operators +category: aggregation +--- + +# $sample + +The `$sample` stage is used in aggregation pipelines to randomly select a specified number of documents from a collection. The `$sample` command is useful during testing, data analysis, and generating random subsets of data for machine learning. + +## Syntax + +```javascript +{ + $sample: { size: } +} +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **`size`** | The number of documents to randomly select from the collection| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Randomly select five documents and project the corresponding document IDs + +```javascript + db.stores.aggregate([{ + $sample: { + size: 5 + } + }, { + $project: { + _id: 1 + } + }]) +``` + +This query returns the following results: + +```json +[ + { "_id": "f7ae8b40-0c66-4e80-9261-ab31bbabffb4" }, + { "_id": "25350272-6797-4f98-91f8-fe79084755c7" }, + { "_id": "c7fd1d22-1a29-4cb0-9155-1ad71d600c2b" }, + { "_id": "e602b444-9519-42e3-a2e1-b5a3da5f6e64" }, + { "_id": "189c239a-edca-434b-baae-aada3a27a2c5" } +] +``` diff --git a/api-reference/operators/aggregation/$set.md b/api-reference/operators/aggregation/$set.md new file mode 100644 index 0000000..35dcbc0 --- /dev/null +++ b/api-reference/operators/aggregation/$set.md @@ -0,0 +1,211 @@ +--- +title: $set +description: The $set operator in DocumentDB updates or creates a new field with a specified value +type: operators +category: aggregation +--- + +# $set + +The `$set` operator updates an existing field or creates a new field with the specified value if it does not exist. One or more fields listed are updated or created. The dot notation is used to update or create nested objects. + +## Syntax + +```javascript +{ + $set: { + newField: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`newField`** | The name of the field to update or create| +| **`expression`** | The expression that defines the value of the new or updated field| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Update an existing field + +```javascript +db.stores.updateOne({ + _id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0" + }, + { + $set: { + name: "Lakeshore Retail" + } + }) +``` + +### Example 2 - Update an existing field in a nested object + +```javascript +db.stores.updateOne({ + _id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0" + }, + { + $set: { + "staff.totalStaff.partTime": 9 + } + }) +``` + +### Example 3 - Create a new field that does not exist + +Create a new field called "formerName" with the old name of the store. + +```javascript +db.stores.updateOne({ + _id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0" + }, + { + $set: { + formerName: "Tailwind Traders | Drone Shoppe - New Theodora" + } + }) +``` + +### Example 4 - Create a new field in a nested object + +Create a new field within the nested totalStaff object to specify a count of temporary staff members. + +```javascript +db.stores.updateOne({ + _id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0" + }, + { + $set: { + "staff.totalStaff.temporary": 3 + } + }) +``` + +### Example 5 - Update multiple fields + +```javascript +db.stores.updateOne({ + _id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0" + }, + { + $set: { + "staff.totalStaff.partTime": 9, + "sales.totalSales": 3611 + } + }) +``` diff --git a/api-reference/operators/aggregation/$skip.md b/api-reference/operators/aggregation/$skip.md new file mode 100644 index 0000000..f5a025d --- /dev/null +++ b/api-reference/operators/aggregation/$skip.md @@ -0,0 +1,355 @@ +--- +title: $skip +description: The $skip stage in the aggregation pipeline is used to skip a specified number of documents from the input and pass the remaining documents to the next stage in the pipeline. +type: operators +category: aggregation +--- + +# $skip + +The $skip stage in the aggregation pipeline is used to skip a specified number of documents from the input and pass the remaining documents to the next stage in the pipeline. The stage is useful for implementing pagination in queries and for controlling the subset of documents that subsequent stages in the pipeline operate on. + +## Syntax + +```javascript +{ + $skip: +} +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **`number`** | The number of documents to skip before passing the remaining documents to the next stage. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + _id: '0fcc0bf0-ed18-4ab8-b558-9848e18058f4', + name: 'First Up Consultants | Beverage Shop - Satterfieldmouth', + location: { lat: -89.2384, lon: -46.4012 }, + staff: { employeeCount: { fullTime: 2, partTime: 20 } }, + sales: { + salesByCategory: [ + { categoryName: 'Wine Accessories', totalSales: 34450 }, + { categoryName: 'Bitters', totalSales: 39496 }, + { categoryName: 'Rum', totalSales: 1734 } + ], + revenue: 75670 + }, + promotionEvents: [ + { + eventName: 'Unbeatable Bargain Bash', + promotionalDates: { + startDate: { Year: 2024, Month: 6, Day: 23 }, + endDate: { Year: 2024, Month: 7, Day: 2 } + }, + discounts: [ + { categoryName: 'Whiskey', discountPercentage: 7 }, + { categoryName: 'Bitters', discountPercentage: 15 }, + { categoryName: 'Brandy', discountPercentage: 8 }, + { categoryName: 'Sports Drinks', discountPercentage: 22 }, + { categoryName: 'Vodka', discountPercentage: 19 } + ] + }, + { + eventName: 'Steal of a Deal Days', + promotionalDates: { + startDate: { Year: 2024, Month: 9, Day: 21 }, + endDate: { Year: 2024, Month: 9, Day: 29 } + }, + discounts: [ + { categoryName: 'Organic Wine', discountPercentage: 19 }, + { categoryName: 'White Wine', discountPercentage: 20 }, + { categoryName: 'Sparkling Wine', discountPercentage: 19 }, + { categoryName: 'Whiskey', discountPercentage: 17 }, + { categoryName: 'Vodka', discountPercentage: 23 } + ] + }, + { + eventName: 'Summer Sale', + promotionalDates: { + startDate: { Year: 2024, Month: 6, Day: 1 }, + endDate: { Year: 2024, Month: 6, Day: 15 } + }, + discounts: [ { categoryName: 'DJ Speakers', discountPercentage: 20 } ] + } + ], + company: 'First Up Consultants', + city: 'Satterfieldmouth', + storeOpeningDate: ISODate("2024-09-20T18:28:57.302Z"), + lastUpdated: Timestamp({ t: 1729448937, i: 1 }), + store: { promotionEvents: null }, + tag: [ '#ShopLocal' ] + } +``` + +### Example 1: Skipping documents in a collection + +To skip the first 2 documents and return the rest, you can use the following aggregation pipeline: + +```javascript +db.stores.aggregate([ + { $skip: 2 } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "promotionEvents": ["Summer Sale", "Black Friday", "Holiday Deals"] + } + }, + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c6", + "store": { + "name": "Uptown Store", + "promotionEvents": ["Back to School", "Winter Sale"] + } + } +] +``` + +### Example 2: Skipping documents and then limiting the result + +To skip the first 2 documents and then limit the result to the next 3 documents, you can combine $skip with $limit: + +```javascript +db.stores.aggregate([ + { $skip: 2 }, + { $limit: 3 } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "728c068a-638c-40af-9172-8ccfa7dddb49", + "name": "Contoso, Ltd. | Book Store - Lake Myron", + "location": { + "lat": 29.416, + "lon": 21.5231 + }, + "staff": { + "employeeCount": { + "fullTime": 7, + "partTime": 16 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "Science Fiction", + "totalSales": 34879 + } + ], + "revenue": 34879 + }, + "promotionEvents": [ + { + "eventName": "Blowout Bonanza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Children's Books", + "discountPercentage": 11 + }, + { + "categoryName": "Fiction", + "discountPercentage": 21 + } + ] + } + ], + "company": "Contoso, Ltd.", + "city": "Lake Myron", + "storeOpeningDate": "ISODate('2024-09-28T18:23:21.591Z')", + "lastUpdated": "Timestamp({ t: 1730139801, i: 1 })", + "storeFeatures": 239 + }, + { + "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", + "name": "Fourth Coffee | Storage Solution Gallery - Port Camilla", + "location": { + "lat": 78.3889, + "lon": 0.6784 + }, + "staff": { + "employeeCount": { + "fullTime": 17, + "partTime": 15 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "Storage Boxes", + "totalSales": 2236 + } + ], + "revenue": 2236 + }, + "promotionEvents": [ + { + "eventName": "Major Discount Mania", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 3 + } + }, + "discounts": [ + { + "categoryName": "Bathroom Storage", + "discountPercentage": 19 + }, + { + "categoryName": "Kitchen Storage", + "discountPercentage": 10 + } + ] + }, + { + "eventName": "Flash Deal Frenzy", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Under-Bed Storage", + "discountPercentage": 20 + }, + { + "categoryName": "Closet Organizers", + "discountPercentage": 21 + } + ] + } + ], + "company": "Fourth Coffee", + "city": "Port Camilla", + "storeOpeningDate": "ISODate('2024-09-23T06:02:53.844Z')", + "lastUpdated": "Timestamp({ t: 1729663373, i: 1 })", + "storeFeatures": 222 + } +] +``` + +### Example 3: Skipping documents in a complex pipeline + +To skip the first promotion event and then project the remaining events for a specific store: + +```javascript +db.stores.aggregate([ + { $match: { "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", } }, + { $unwind: "$promotionEvents" }, + { $skip: 1 }, + { $project: { "promotionEvents": 1, _id: 0 } } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "promotionEvents": { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + }, + { + "promotionEvents": { + "eventName": "Summer Sale", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 1 + }, + "endDate": { + "Year": 2024, + "Month": 6, + "Day": 15 + } + }, + "discounts": [ + { + "categoryName": "DJ Speakers", + "discountPercentage": 20 + } + ] + } + } +] +``` diff --git a/api-reference/operators/aggregation/$sort.md b/api-reference/operators/aggregation/$sort.md new file mode 100644 index 0000000..dfc9459 --- /dev/null +++ b/api-reference/operators/aggregation/$sort.md @@ -0,0 +1,301 @@ +--- +title: $sort +description: The $sort stage in the aggregation pipeline is used to order the documents in the pipeline by a specified field or fields. +type: operators +category: aggregation +--- + +# $sort + +The $sort stage in the aggregation pipeline is used to order the documents in the pipeline by a specified field or fields. This stage helps you sort data, like arranging sales by amount or events by date. + +## Syntax + +```javascript +{ + $sort: { + < field1 >: < sort order > , + < field2 >: < sort order > + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to sort by | +| **`sort order`** | The order in which we should sort the field. 1 for ascending order and -1 for descending order. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Sorting by total sales in sescending order + +To sort the sales categories by their total sales in descending order: + +```javascript +db.collection.aggregate([ + { + $unwind: "$store.sales.salesByCategory" + }, + { + $sort: { "store.sales.salesByCategory.totalSales": -1 } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "sales": { + "salesByCategory": [ + { + "category": "Electronics", + "totalSales": 15000 + }, + { + "category": "Clothing", + "totalSales": 12000 + }, + { + "category": "Home Goods", + "totalSales": 10000 + } + ] + } + } + }, + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c6", + "store": { + "name": "Uptown Store", + "sales": { + "salesByCategory": [ + { + "category": "Electronics", + "totalSales": 20000 + }, + { + "category": "Clothing", + "totalSales": 18000 + }, + { + "category": "Home Goods", + "totalSales": 15000 + } + ] + } + } + } +] +``` + +### Example 2: Sorting by event start date in ascending order + +To sort the promotion events by their start dates in ascending order: + +```javascript +db.collection.aggregate([ + { + $unwind: "$store.promotionEvents" + }, + { + $sort: { "store.promotionEvents.promotionalDates.startDate": 1 } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "promotionEvents": [ + { + "eventName": "Summer Sale", + "promotionalDates": { + "startDate": "2024-06-01T00:00:00Z", + "endDate": "2024-06-30T23:59:59Z" + } + }, + { + "eventName": "Black Friday", + "promotionalDates": { + "startDate": "2024-11-25T00:00:00Z", + "endDate": "2024-11-25T23:59:59Z" + } + }, + { + "eventName": "Holiday Deals", + "promotionalDates": { + "startDate": "2024-12-01T00:00:00Z", + "endDate": "2024-12-31T23:59:59Z" + } + } + ] + } + }, + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c6", + "store": { + "name": "Uptown Store", + "promotionEvents": [ + { + "eventName": "Back to School", + "promotionalDates": { + "startDate": "2024-08-01T00:00:00Z", + "endDate": "2024-08-31T23:59:59Z" + } + }, + { + "eventName": "Winter Sale", + "promotionalDates": { + "startDate": "2024-12-01T00:00:00Z", + "endDate": "2024-12-31T23:59:59Z" + } + } + ] + } + } +] +``` + +### Example 3: Sorting an array of objects + +The example sorts the `salesByCategory` array in place based on the `totalSales` field in ascending order. + +```javascript +db.stores.updateOne({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" + }, { + $push: { + "sales.salesByCategory": { + $each: [], + $sort: { + totalSales: 1 + } + } + } + } +) +``` diff --git a/api-reference/operators/aggregation/$sortbycount.md b/api-reference/operators/aggregation/$sortbycount.md new file mode 100644 index 0000000..96aba36 --- /dev/null +++ b/api-reference/operators/aggregation/$sortbycount.md @@ -0,0 +1,181 @@ +--- +title: $sortByCount +description: The $sortByCount stage in the aggregation pipeline is used to group documents by a specified expression and then sort the count of documents in each group in descending order. +type: operators +category: aggregation +--- + +# $sortByCount + +The $sortByCount stage in the aggregation pipeline is used to group documents by a specified expression and then sort the count of documents in each group in descending order. The `$sortByCount` stage is useful for quickly identifying the most common values within a dataset. + +## Syntax + +```javascript +{ + $sortByCount: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | This is the field or computed expression on which to group and count the documents. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Group promotion events by name and count occurrences in descending order + +To group by the eventName field and count the number of occurrences of each event name, sorting the results in descending order of the count + +```javascript +db.stores.aggregate([ + { $unwind: "$promotionEvents" }, + { $sortByCount: "$promotionEvents.eventName" } +]) +``` + +This query returns the following results: + +```json +[ + { "_id": "Crazy Deal Days", "count": 4239 }, + { "_id": "Markdown Madness", "count": 2967 }, + { "_id": "Bargain Bonanza", "count": 2925 }, + { "_id": "Crazy Discount Days", "count": 2922 }, + { "_id": "Price Smash Spectacular", "count": 2915 }, + { "_id": "Super Saver Spectacular", "count": 2900 }, + { "_id": "Crazy Markdown Madness", "count": 2899 }, + { "_id": "Price Cut Carnival", "count": 2868 }, + { "_id": "Grand Bargain Bash", "count": 2849 }, + { "_id": "Bargain Blitz Bash", "count": 2843 }, + { "_id": "Grand Savings Gala", "count": 2826 }, + { "_id": "Super Saver Fiesta", "count": 1551 }, + { "_id": "Major Deal Days", "count": 1548 }, + { "_id": "Price Slash Carnival", "count": 1535 }, + { "_id": "Super Discount Days", "count": 1533 }, + { "_id": "Big Deal Bonanza", "count": 1533 }, + { "_id": "Incredible Savings Showcase", "count": 1531 }, + { "_id": "Unbeatable Savings Spectacular", "count": 1518 }, + { "_id": "Fantastic Deal Days", "count": 1511 }, + { "_id": "Flash Bargain Frenzy", "count": 1504 } +] +``` + +This pipeline will: + +1. Use $unwind to deconstruct the promotionEvents array field from the input documents. +2. Use $sortByCount to group by the eventName field and count the number of occurrences of each event name, sorting the results in descending order of the count. diff --git a/api-reference/operators/aggregation/$tobool.md b/api-reference/operators/aggregation/$tobool.md new file mode 100644 index 0000000..0e02e15 --- /dev/null +++ b/api-reference/operators/aggregation/$tobool.md @@ -0,0 +1,241 @@ +--- +title: $toBool +description: The $toBool operator converts an expression into a Boolean type +type: operators +category: aggregation +--- + +# $toBool + +The `$toBool` operator converts an expression into a Boolean value. Boolean values are returned as is without a conversion. Nonzero numeric values are converted to true while Decimal, Long, Double or Int values of 0 are converted to false. All other data types are converted to true. + +## Syntax + +```javascript +{ + $toBool: < expression > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The specified value to convert into a Boolean value| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert a Double value into a Boolean value + +To convert the value of the latitude field from a double to a boolean, run a query using the $toBool operator on the field to make the conversion. Positive numeric values are converted to true. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsBool: { + $toBool: "$location.lat" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeAsBool": true + } +] +``` + +### Example 2: Convert a String value into a Boolean value + +To convert the value of the _id field from a string to a boolean, run a query using the $toBool value to make the conversion. String values are converted to true. + +```javascript + db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } + }, { + $project: { + originalId: "$_id", + idAsBool: { + $toBool: "$_id" + } + } + }]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalId": "b0107631-9370-4acd-aafa-8ac3511e623d", + "idAsBool": true + } +] +``` + +### Example 3: Convert an Int value into a Boolean value + +To convert the value of the sales.totalSales field from integer to boolean, run a query using the $toBool operator to make the conversion. Positive numeric values are converted to true. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalTotalSales: "$sales.totalSales", + totalSalesAsBool: { + $toBool: "$sales.totalSales" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalTotalSales": 9366, + "totalSalesAsBool": true + } +] +``` + +This table delineates the expected behavior of the $toBool operator based on the data type of the input expression. + +| **Value Type** | **Behavior/Output** | +|--------------------------------------------------------------|---------------------| +| Boolean value true | Output -> true | +| Boolean value false | Output -> false | +| Any Double, Int, Long, or Decimal value | Output -> true | +| Any ISODate value | Output -> true | +| Null value | Output -> null | diff --git a/api-reference/operators/aggregation/$todate.md b/api-reference/operators/aggregation/$todate.md new file mode 100644 index 0000000..3bc1f0a --- /dev/null +++ b/api-reference/operators/aggregation/$todate.md @@ -0,0 +1,173 @@ +--- +title: $toDate +description: The $toDate operator converts supported types to a proper Date object. +type: operators +category: aggregation +--- + +# $toDate + +The `$toDate` operator converts a specified value into a date type. + +## Syntax + +```javascript +{ + $toDate: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | An expression that can be converted to a date. Supported formats include: ISO date strings, milliseconds since Unix epoch (number), ObjectId, and Timestamp. If the expression can't be converted to a date, the operation returns an error. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert timestamp to date + +To convert the value of the lastUpdated field from a Unix timestamp to a date format, run a query using the $toDate operator to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "905d1939-e03a-413e-a9c4-221f74055aac" + } + }, + { + $project: { + name: 1, + lastUpdated: 1, + lastUpdatedAsDate: { + $toDate: "$lastUpdated" + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "lastUpdated": { "t": 1729983325, "i": 1 }, + "lastUpdatedAsDate": ISODate("2024-10-26T22:55:25.000Z") + } +] +``` diff --git a/api-reference/operators/aggregation/$todecimal.md b/api-reference/operators/aggregation/$todecimal.md new file mode 100644 index 0000000..570b8cd --- /dev/null +++ b/api-reference/operators/aggregation/$todecimal.md @@ -0,0 +1,198 @@ +--- +title: $toDecimal +description: The $toDecimal operator converts an expression into a Decimal type +type: operators +category: aggregation +--- + +# $toDecimal + +The `$toDecimal` operator converts an input expression into a Decimal value. Long, Double or Int values are simply converted to a Decimal data type, while Decimal values are returned as is. A boolean value of true is converted to 1, while a boolean false is converted to 0. Lastly, ISODates are converted to a Decimal value corresponding to the number of milliseconds since January 1st, 1970 represented by the ISODate value. + +## Syntax + +```javascript +{ + $toDecimal: < expression > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The specified value to convert into a Decimal value| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert a Double value into a Decimal value + +To convert the value of the latitude field from a double to a decimal value, run a query using the $toDecimal operator to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsDecimal: { + $toDecimal: "$location.lat" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeAsDecimal": "Decimal128('72.8377000000000')" + } +] +``` + +### Example 2: Convert an ISODate value into a Decimal value + +To convert an ISODate to a decimal value, run a query using the $toDecimal operator on the value to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + dateAsDecimal: { + $toDecimal: ISODate("2025-01-06T00:00:00.000Z") + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "dateAsDecimal": "Decimal128('1736121600000')" + } +] +``` diff --git a/api-reference/operators/aggregation/$todouble.md b/api-reference/operators/aggregation/$todouble.md new file mode 100644 index 0000000..9d116b8 --- /dev/null +++ b/api-reference/operators/aggregation/$todouble.md @@ -0,0 +1,181 @@ +--- +title: $toDouble +description: The $toDouble operator converts an expression into a Double value +type: operators +category: aggregation +--- + +# $toDouble + +The `$toDouble` operator converts a specified value into a Double value. + +## Syntax + +```javascript +{ + $toDouble: < expression > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The specified value to convert into a Double value | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert a String value into a Double value + +To convert the string representation of 72 ("72") into a double value, run a query using the $toDouble operator on the string to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsDouble: { + $toDouble: { + $toString: "72" + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeAsDouble": 72 + } +] +``` + +This table delineates the expected behavior of the $toDouble operator based on the data type of the input value. + +| **Value Type** | **Behavior/Output** | +|--------------------------------------------------------------|---------------------| +| Boolean value true | Output -> 1 | +| Boolean value false | Output -> 0 | +| Double value. E.g., 72.0 | Output -> 72 | +| String representation of a number value. For example, "72" | Output -> 72 | +| Null value | Output -> null | diff --git a/api-reference/operators/aggregation/$toint.md b/api-reference/operators/aggregation/$toint.md new file mode 100644 index 0000000..839beba --- /dev/null +++ b/api-reference/operators/aggregation/$toint.md @@ -0,0 +1,236 @@ +--- +title: $toInt +description: The $toInt operator converts an expression into an Integer +type: operators +category: aggregation +--- + +# $toInt + +The `$toInt` operator converts a specified value into an integer value. + +## Syntax + +The syntax for the `$toInt` operator is: + +```javascript +{ + $toInt: < expression > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The specified value to convert into an Integer value| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert a Double value into an Integer value + +To convert the value of the latitude field from a double to an int, run a query using the $toInt operator on the field to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsInt: { + $toInt: "$location.lat" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeAsInt": 72 + } +] +``` + +### Example 2: Convert a String value into an Integer value + +To convert the string representation of 72 ("72") to an integer value, run a query using the $toInt operator on the value to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsInt: { + $toInt: { + $toString: "72" + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeAsInt": 72 + } +] +``` + +However, the following query returns an error since the string "72.0" isn't the string representation of an integer value. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsInt: { + $toInt: { + $toString: "72.0" + } + } + } +}]) +``` + +This query returns the following error message - "Failed to parse number '72.0' in $convert" + +This table delineates the expected behavior of the $toInt operator based on the data type of the input. + +| **Value Type** | **Behavior/Output** | +|--------------------------------------------------------------|---------------------| +| Boolean value true | Output -> 1 | +| Boolean value false | Output -> 0 | +| Double value. E.g., 72.0 | Output -> 72 | +| String representation of an integer value. For example, "72" | Output -> 72 | +| String representation of a double value. For example, "72.0" | Output -> Error | +| Null value | Output -> null | diff --git a/api-reference/operators/aggregation/$tolong.md b/api-reference/operators/aggregation/$tolong.md new file mode 100644 index 0000000..204c6af --- /dev/null +++ b/api-reference/operators/aggregation/$tolong.md @@ -0,0 +1,213 @@ +--- +title: $toLong +description: The $toLong operator converts an expression into a Long value +type: operators +category: aggregation +--- + +# $toLong + +The `$toLong` operator converts a specified value into a Long value. + +## Syntax + +```javascript +{ + $toLong: < expression > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The specified value to convert into a long value| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert a Double value into a Long value + +To convert the value of the latitude field from a Double to a Long value, run a query using the $toLong operator on the field to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsLong: { + $toLong: "$location.lat" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeAsLong": "Long('72')" + } +] +``` + +### Example 2: Convert a String value into a Long value + +To convert the string representation of 72 ("72") into a Long value, run a query using the $toLong operator on the string to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsLong: { + $toLong: { + $toString: "72" + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeAsLong": Long('72') + } +] +``` + +This table delineates the expected behavior of the $toLong operator based on the data type of the input value. + +| **Value Type** | **Behavior/Output** | +|--------------------------------------------------------------|---------------------| +| Boolean value true | Output -> Long("1") | +| Boolean value false | Output -> Long("1") | +| Double value. E.g., 72.0 | Output -> Long("72")| +| String representation of a long value. For example, "72" | Output -> Long("72")| +| String representation of a double value. For example, "72.0" | Output -> Error | +| Null value | Output -> null | diff --git a/api-reference/operators/aggregation/$toobjectid.md b/api-reference/operators/aggregation/$toobjectid.md new file mode 100644 index 0000000..2edb11c --- /dev/null +++ b/api-reference/operators/aggregation/$toobjectid.md @@ -0,0 +1,175 @@ +--- +title: $toObjectId +description: The $toObjectId operator converts an expression into an ObjectId +type: operators +category: aggregation +--- + +# $toObjectId + +The `$toObject` operator converts a specified value into an ObjectId. + +## Syntax + +```javascript +{ + $toObject: < expression > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The specified string value to convert into an ObjectId| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert the first 24 alphanumeric characters in the _id field into an ObjectId value + +To remove all occurrences of the "-" character and convert the first twenty four characters in the _id field into an ObjectId, run a query using the $toObjectId on a substring of the modified _id field to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + idAsObjectId: { + $toObjectId: { + $substr: [{ + $replaceAll: { + input: "$_id", + find: "-", + replacement: "" + } + }, 0, 24] + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "idAsObjectId": "ObjectId('b010763193704acdaafa8ac3')" + } +] +``` diff --git a/api-reference/operators/aggregation/$tostring.md b/api-reference/operators/aggregation/$tostring.md new file mode 100644 index 0000000..a2d6db4 --- /dev/null +++ b/api-reference/operators/aggregation/$tostring.md @@ -0,0 +1,209 @@ +--- +title: $toString +description: The $toString operator converts an expression into a String +type: operators +category: aggregation +--- + +# $toString + +The `$toString` operator simply returns the value of the specified expression as a String. + +## Syntax + +```javascript +{ + $toString: < expression > +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | The specified value to convert into a String value| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert a Double value into a String value + +To convert the value of the latitude field from a Double to a String, run a query using the $toString operator on the field to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalLatitude: "$location.lat", + latitudeAsString: { + $toString: "$location.lat" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalLatitude": 72.8377, + "latitudeAsString": "72.8377" + } +] +``` + +### Example 2: Convert an Int value into a String value + +To convert the value of the totalSales field from an Int to a String, run a query using the $toString operator on the field to make the conversion. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "b0107631-9370-4acd-aafa-8ac3511e623d" + } +}, { + $project: { + originalTotalSales: "$sales.totalSales", + totalSalesAsString: { + $toString: "$sales.totalSales" + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "b0107631-9370-4acd-aafa-8ac3511e623d", + "originalTotalSales": 9366, + "totalSalesAsString": "9366" + } +] +``` + +This table delineates the expected behavior of the $toString operator based on the data type of the input value. + +| **Value Type** | **Behavior/Output** | +|------------------------------------------------------------------------|--------------------------------------| +| Boolean value true | Output -> "true" | +| Boolean value false | Output -> "false" | +| Any Double, Int, Long or Decimal value. For example, 72 | Output -> "72" | +| Any ObjectId value. For example, ObjectId("b010763193704acdaafa8ac3") | Output -> "b010763193704acdaafa8ac3" | diff --git a/api-reference/operators/aggregation/$unset.md b/api-reference/operators/aggregation/$unset.md new file mode 100644 index 0000000..ccc1b87 --- /dev/null +++ b/api-reference/operators/aggregation/$unset.md @@ -0,0 +1,244 @@ +--- +title: $unset +description: The $unset stage in the aggregation pipeline is used to remove specified fields from documents. +type: operators +category: aggregation +--- + +# $unset + +The $unset stage the aggregation pipeline is used to remove specified fields from documents. This can be particularly useful when you need to exclude certain fields from the results of an aggregation query for reasons such as privacy, reducing payload size, or simply cleaning up the output. + +## Syntax + +```javascript +{ + $unset: "" | ["", "", ...] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field1, field2, ...`** | The names of the fields to remove from the documents. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Remove a single field + +To remove the location field from the documents. + +```javascript +db.stores.aggregate([ + { + $unset: "store.location" + } +]) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "sales": { + "totalSales": 15000, + "salesByCategory": [ + { + "category": "Electronics", + "totalSales": 5000 + }, + { + "category": "Clothing", + "totalSales": 10000 + } + ] + } + } + } +] +``` + +### Example 2: Remove multiple fields + +To remove the location and sales.totalSales fields from the documents. + +```javascript +db.stores.aggregate([ + { + $unset: ["store.location", "store.sales.totalSales"] + } +]) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "sales": { + "salesByCategory": [ + { + "category": "Electronics", + "totalSales": 5000 + }, + { + "category": "Clothing", + "totalSales": 10000 + } + ] + } + } + } +] +``` + +### Example 3: Remove nested fields + +To remove the staff.totalStaff.fullTime and promotionEvents.discounts fields from the documents. + +```javascript +db.stores.aggregate([ + { + $unset: ["store.staff.totalStaff.fullTime", "store.promotionEvents.discounts"] + } +]) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "staff": { + "totalStaff": { + "partTime": 8 + } + }, + "promotionEvents": ["Summer Sale", "Black Friday", "Holiday Deals"] + } + } +] +``` diff --git a/api-reference/operators/aggregation/$unwind.md b/api-reference/operators/aggregation/$unwind.md new file mode 100644 index 0000000..28d6f26 --- /dev/null +++ b/api-reference/operators/aggregation/$unwind.md @@ -0,0 +1,277 @@ +--- +title: $unwind +description: The $unwind stage in the aggregation framework is used to deconstruct an array field from the input documents to output a document for each element. +type: operators +category: aggregation +--- + +# $unwind + +The $unwind stage in the aggregation framework is used to deconstruct an array field from the input documents to output a document for each element. Each output document is a copy of the original but with the value of the array field replaced by a single element. This is particularly useful for normalizing data stored in arrays and for performing operations on each element of an array separately. + +## Syntax + +```javascript +{ + $unwind: { + path: , + includeArrayIndex: , // Optional + preserveNullAndEmptyArrays: // Optional + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`path`** | The field path to an array field. This is a required parameter. | +| **`includeArrayIndex`** | Optional. The name of a new field to hold the array index of the unwound element. | +| **`preserveNullAndEmptyArrays`** | Optional. If true, if the path is null, missing, or an empty array, `$unwind` outputs the document unchanged. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Unwind sales by category + +To deconstruct the salesByCategory array in the store document: + +```javascript +db.stores.aggregate([ + { + $unwind: "$sales.salesByCategory" + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "sales": { + "totalSales": 15000, + "salesByCategory": { + "category": "Electronics", + "totalSales": 5000 + } + } + } + }, + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "sales": { + "totalSales": 15000, + "salesByCategory": { + "category": "Clothing", + "totalSales": 10000 + } + } + } + } +] +``` + +### Example 2: Unwind promotion events with array index + +To deconstruct the promotionEvents array and include the array index in the output: + +```javascript +db.stores.aggregate([ + { + $unwind: { + path: "$promotionEvents", + includeArrayIndex: "eventIndex" + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "promotionEvents": { + "eventName": "Summer Sale", + "eventDate": ISODate("2024-08-01T00:00:00Z") + }, + "eventIndex": 0 + } + }, + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "promotionEvents": { + "eventName": "Black Friday", + "eventDate": ISODate("2024-11-25T00:00:00Z") + }, + "eventIndex": 1 + } + } +] +``` + +### Example 3: Unwind discounts within pomotion events + +To deconstruct the discounts array within each promotion event and preserve documents with no discounts: + +```javascript +db.stores.aggregate([ + { + $unwind: { + path: "$promotionEvents.discounts", + preserveNullAndEmptyArrays: true + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "promotionEvents": { + "eventName": "Summer Sale", + "discounts": { + "discountType": "Percentage", + "discountAmount": 20 + } + } + } + }, + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "store": { + "name": "Downtown Store", + "promotionEvents": { + "eventName": "Black Friday" + } + } + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$abs.md b/api-reference/operators/arithmetic-expression/$abs.md new file mode 100644 index 0000000..60541f2 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$abs.md @@ -0,0 +1,209 @@ +--- +title: $abs +description: The $abs operator returns the absolute value of a number. +type: operators +category: arithmetic-expression +--- + +# $abs + +The `$abs` operator returns the absolute value of a number. It removes any negative sign from a number, making it positive. + +## Syntax + +```javascript +{ + $abs: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any expression that resolves to a number. If the expression is null or refers to a missing field, $abs returns null. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Use the absolute value of total sales + +To calculate the absolute difference in sales volume of each category and the average sales across all categories for a store, first run a query to filter on the specific store. Then, calculate the difference in sales between each category and the average across all categories. Lastly, project the absolute difference using the $abs operator. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } +}, { + $project: { + name: 1, + salesByCategory: { + $map: { + input: "$sales.salesByCategory", + as: "category", + in: { + categoryName: "$$category.categoryName", + totalSales: "$$category.totalSales", + differenceFromAverage: { + $abs: { + $subtract: ["$$category.totalSales", { + $avg: "$sales.salesByCategory.totalSales" + }] + } + } + } + } + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "salesByCategory": [ + { + "categoryName": "Sound Bars", + "totalSales": 2120, + "differenceFromAverage": 28252.8 + }, + { + "categoryName": "Home Theater Projectors", + "totalSales": 45004, + "differenceFromAverage": 14631.2 + }, + { + "categoryName": "Game Controllers", + "totalSales": 43522, + "differenceFromAverage": 13149.2 + }, + { + "categoryName": "Remote Controls", + "totalSales": 28946, + "differenceFromAverage": 1426.8 + }, + { + "categoryName": "VR Games", + "totalSales": 32272, + "differenceFromAverage": 1899.2 + } + ] + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$add.md b/api-reference/operators/arithmetic-expression/$add.md new file mode 100644 index 0000000..3c3961f --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$add.md @@ -0,0 +1,173 @@ +--- +title: $add +description: The $add operator returns the sum of two numbers or the sum of a date and numbers. +type: operators +category: arithmetic-expression +--- + +# $add + +The `$add` operator adds numbers together or adds numbers and dates. When adding numbers and dates, the numbers are interpreted as milliseconds. + +## Syntax + +```javascript +{ + $add: [ ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid expressions that resolve to numbers or dates. The expressions can be any combination of numbers and dates. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Get the current and project staff count + +To calculate the total staff and project the total staff looking forward, use the $add operator on the nested totalStaff object to return the desired results. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } +}, { + $project: { + name: 1, + currentTotalStaff: { + $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + }, + projectedNextYearStaff: { + $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime", 2] + } + } +}]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "currentTotalStaff": 39, + "projectedNextYearStaff": 41 + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$ceil.md b/api-reference/operators/arithmetic-expression/$ceil.md new file mode 100644 index 0000000..adde026 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$ceil.md @@ -0,0 +1,184 @@ +--- +title: $ceil +description: The $ceil operator returns the smallest integer greater than or equal to the specified number. +type: operators +category: arithmetic-expression +--- + +# $ceil + +The `$ceil` operator computes the ceiling of the input number. This operator returns the smallest integer value that is greater than or equal to the input. + +## Syntax + +```javascript +{ + $ceil: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The input number whose ceiling needs to be returned. For a null or missing field, $ceil returns null. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the ceiling of average sales volume per employee + +To calculate the ceiling of the sales volume per employee, first run a query to divide the total sales for the store by the number of staff. Then, use the $ceil operator to return the ceiling of the calculated value. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + totalSales: "$sales.totalSales", + totalStaff: { + $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + }, + ceiledAverageSalesPerStaff: { + $ceil: { + $divide: [ + "$sales.totalSales", + { + $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + } + ] + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "totalSales": 151864, + "totalStaff": 39, + "ceiledAverageSalesPerStaff": 3894 + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$divide.md b/api-reference/operators/arithmetic-expression/$divide.md new file mode 100644 index 0000000..7e01e1d --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$divide.md @@ -0,0 +1,188 @@ +--- +title: $divide +description: The $divide operator divides two numbers and returns the quotient. +type: operators +category: arithmetic-expression +--- + +# $divide + +The `$divide` operator divides two numbers and returns the quotient. The $divide operator returns an error if the divisor is zero. + +## Syntax + +```javascript +{ + $divide: [ , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid expression that resolves to a number to be divided. | +| **``** | Any valid expression that resolves to a nonzero number to divide by. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the average sales volume per employee + +To calculate the average sales volume per employee, first run a query using the $divide operator to divide the total sales by the staff count. To calculate the percentage of full time staff, use the $divide operator to dive the number of full time staff by the total staff count and project the result as a percentage. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + averageSalesPerStaff: { + $divide: [ + "$sales.totalSales", + { + $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + } + ] + }, + fullTimeStaffPercentage: { + $multiply: [{ + $divide: [ + "$staff.totalStaff.fullTime", + { + $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + } + ] + }, 100] + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "averageSalesPerStaff": 3893.95, + "fullTimeStaffPercentage": 48.72 + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$exp.md b/api-reference/operators/arithmetic-expression/$exp.md new file mode 100644 index 0000000..60dec9c --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$exp.md @@ -0,0 +1,191 @@ +--- +title: $exp +description: The $exp operator raises e to the specified exponent and returns the result +type: operators +category: arithmetic-expression +--- + +# $exp + +The `$exp` operator returns the value of e raised to the specified exponent. The mathematical constant e is approximately equal to 2.71828. + +## Syntax + +```javascript +{ + $exp: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid expression that resolves to a number. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate exponential growth rate + +To calculate the exponential growth rate of total sales volume of a store by 10% and 20% respectively, use the $exp operator to multiple the value of the totalSales field by e^0.1 and e^0.2. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + currentSales: "$sales.totalSales", + projectedGrowth: { + oneYear: { + $multiply: [ + "$sales.totalSales", + { + $exp: 0.1 + } // 10% growth rate + ] + }, + twoYears: { + $multiply: [ + "$sales.totalSales", + { + $exp: 0.2 + } // 20% growth rate + ] + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "currentSales": 151864, + "projectedGrowth": { + "oneYear": 167809.93, + "twoYears": 185304.95 + } + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$floor.md b/api-reference/operators/arithmetic-expression/$floor.md new file mode 100644 index 0000000..9c3be01 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$floor.md @@ -0,0 +1,212 @@ +--- +title: $floor +description: The $floor operator returns the largest integer less than or equal to the specified number +type: operators +category: arithmetic-expression +--- + +# $floor + +The `$floor` operator returns the largest integer less than or equal to the specified number. + +## Syntax + +```javascript +{ + $floor: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid expression that resolves to a number. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the floor of total sales and discounts + +To calculate the floor of the average sales volume for a given store and the floor of sales per category, run a query using the $floor operator to return the desired results. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + averageSalesFloor: { + $floor: { + $divide: [ + "$sales.totalSales", + { + $size: "$sales.salesByCategory" + } + ] + } + }, + categoriesWithFloorSales: { + $map: { + input: "$sales.salesByCategory", + as: "category", + in: { + categoryName: "$$category.categoryName", + floorSales: { + $floor: "$$category.totalSales" + } + } + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "averageSalesFloor": 30372, + "categoriesWithFloorSales": [ + { + "categoryName": "Sound Bars", + "floorSales": 2120 + }, + { + "categoryName": "Home Theater Projectors", + "floorSales": 45004 + }, + { + "categoryName": "Game Controllers", + "floorSales": 43522 + }, + { + "categoryName": "Remote Controls", + "floorSales": 28946 + }, + { + "categoryName": "VR Games", + "floorSales": 32272 + } + ] + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$ln.md b/api-reference/operators/arithmetic-expression/$ln.md new file mode 100644 index 0000000..6e04dfe --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$ln.md @@ -0,0 +1,207 @@ +--- +title: $ln +description: The $ln operator calculates the natural logarithm of the input +type: operators +category: arithmetic-expression +--- + +# $ln + +The `$ln` operator calculates the natural logarithm (base e) of the input number. + +## Syntax + +```javascript +{ + $ln: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid expression that resolves to a positive number. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the natural logarithm of total sales by category + +To calculate the natural logarithm of sales volume by category to analyze growth rates, run a query using the $ln operator on the totalSales field to return the desired result. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + salesGrowthMetrics: { + $map: { + input: "$sales.salesByCategory", + as: "category", + in: { + categoryName: "$$category.categoryName", + salesValue: "$$category.totalSales", + naturalLog: { + $ln: "$$category.totalSales" + } + } + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "salesGrowthMetrics": [ + { + "categoryName": "Sound Bars", + "salesValue": 2120, + "naturalLog": 7.659 + }, + { + "categoryName": "Home Theater Projectors", + "salesValue": 45004, + "naturalLog": 10.714 + }, + { + "categoryName": "Game Controllers", + "salesValue": 43522, + "naturalLog": 10.681 + }, + { + "categoryName": "Remote Controls", + "salesValue": 28946, + "naturalLog": 10.273 + }, + { + "categoryName": "VR Games", + "salesValue": 32272, + "naturalLog": 10.382 + } + ] + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$log.md b/api-reference/operators/arithmetic-expression/$log.md new file mode 100644 index 0000000..cb4fa7e --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$log.md @@ -0,0 +1,216 @@ +--- +title: $log +description: The $log operator calculates the logarithm of a number in the specified base +type: operators +category: arithmetic-expression +--- + +# $log + +The `$log` operator calculates the logarithm of a number in the specified base. + +## Syntax + +```javascript +{ + $log: [ , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid expression that resolves to a positive number. | +| **``** | Any valid expression that resolves to a positive number to be used as the logarithm base. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the log of total sales + +To calculate the log of sales volumes per category in base 2 and 10, run a query using the $log operator on the totalSales field with bases 2 and 10 respectively to return the desired result. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + categoryAnalysis: { + $map: { + input: "$sales.salesByCategory", + as: "category", + in: { + categoryName: "$$category.categoryName", + sales: "$$category.totalSales", + logBase2: { + $log: ["$$category.totalSales", 2] + }, + logBase10: { + $log: ["$$category.totalSales", 10] + } + } + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "categoryAnalysis": [ + { + "categoryName": "Sound Bars", + "sales": 2120, + "logBase2": 11.051, + "logBase10": 3.326 + }, + { + "categoryName": "Home Theater Projectors", + "sales": 45004, + "logBase2": 15.458, + "logBase10": 4.653 + }, + { + "categoryName": "Game Controllers", + "sales": 43522, + "logBase2": 15.410, + "logBase10": 4.639 + }, + { + "categoryName": "Remote Controls", + "sales": 28946, + "logBase2": 14.822, + "logBase10": 4.462 + }, + { + "categoryName": "VR Games", + "sales": 32272, + "logBase2": 14.977, + "logBase10": 4.509 + } + ] + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$log10.md b/api-reference/operators/arithmetic-expression/$log10.md new file mode 100644 index 0000000..3923ff5 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$log10.md @@ -0,0 +1,242 @@ +--- +title: $log10 +description: The $log10 operator calculates the log of a specified number in base 10 +type: operators +category: arithmetic-expression +--- + +# $log10 + +The `$log10` operator calculates the logarithm of a number in base 10 and returns the result. + +## Syntax + +```javascript +{ + $log10: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid expression that resolves to a positive number. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Analyze sales distribution + +To bucket the distribution of sales per category within a store, run a query using the $log10 operator on the totalSales field. Then, bucket the categories into "Low", "Medium" and "High" based on the result. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + salesAnalysis: { + $map: { + input: "$sales.salesByCategory", + as: "category", + in: { + categoryName: "$$category.categoryName", + originalSales: "$$category.totalSales", + logScale: { + $log10: "$$category.totalSales" + }, + magnitudeClass: { + $switch: { + branches: [{ + case: { + $lt: [{ + $log10: "$$category.totalSales" + }, 3] + }, + then: "Low" + }, + { + case: { + $lt: [{ + $log10: "$$category.totalSales" + }, 4] + }, + then: "Medium" + }, + { + case: { + $lt: [{ + $log10: "$$category.totalSales" + }, 5] + }, + then: "High" + } + ], + default: "Very High" + } + } + } + } + } + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "salesAnalysis": [ + { + "categoryName": "Sound Bars", + "originalSales": 2120, + "logScale": 3.326, + "magnitudeClass": "Medium" + }, + { + "categoryName": "Home Theater Projectors", + "originalSales": 45004, + "logScale": 4.653, + "magnitudeClass": "High" + }, + { + "categoryName": "Game Controllers", + "originalSales": 43522, + "logScale": 4.639, + "magnitudeClass": "High" + }, + { + "categoryName": "Remote Controls", + "originalSales": 28946, + "logScale": 4.462, + "magnitudeClass": "High" + }, + { + "categoryName": "VR Games", + "originalSales": 32272, + "logScale": 4.509, + "magnitudeClass": "High" + } + ] + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$multiply.md b/api-reference/operators/arithmetic-expression/$multiply.md new file mode 100644 index 0000000..9bc9bbb --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$multiply.md @@ -0,0 +1,196 @@ +--- +title: $multiply +description: The $multiply operator multiplies the input numerical values +type: operators +category: arithmetic-expression +--- + +# $multiply + +The `$multiply` operator calculates the product of the specified input numerical values. + +## Syntax + +```javascript +{ + $multiply: [ ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +|**``**| A comma separated list of numerical values. + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Multiply a field by a constant + +To double the total sales for all stores under the "First Up Consultants" company, first run a query to filter on the name of the company. Then, use the $multiply operator on the totalSales field to return the desired results. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $project: { + company: 1, + "sales.revenue": 1, + salesVolumeDoubled: { + $multiply: ["$sales.revenue", 2] + } + } +}]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "sales": { + "revenue": 279183 + }, + "company": "First Up Consultants", + "salesVolumeDoubled": 558366 + }, + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "sales": { + "revenue": 50000 + }, + "company": "First Up Consultants", + "salesVolumeDoubled": 100000 + }, + { + "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad", + "sales": { + "revenue": 68508 + }, + "company": "First Up Consultants", + "salesVolumeDoubled": 137016 + } +] +``` + +## Limitations + +- The `$multiply` operator works only with numerical expressions. Using it with non-numerical values result in an error. +- Be cautious of overflow or precision issues when working with large numbers or floating-point arithmetic. diff --git a/api-reference/operators/arithmetic-expression/$pow.md b/api-reference/operators/arithmetic-expression/$pow.md new file mode 100644 index 0000000..d981e02 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$pow.md @@ -0,0 +1,192 @@ +--- +title: $pow +description: The `$pow` operator calculates the value of a numerical value raised to the power of a specified exponent. +type: operators +category: arithmetic-expression +--- + +# $pow + +The `$pow` operator calculates the value of a number raised to a specified exponent. + +## Syntax + +```javascript +{ + $pow: [ , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The base number to be raised to the exponent. | +| **``** | The exponent to raise the base number to. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculate the square of total sales volume + +To calculate the square of the sales volume of all stores under the "First Up Consultants" company, first run a query to filter on the name of the company. Then, use the $power operator on the nested fullSales field to calculate the desired result. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $project: { + company: 1, + "sales.revenue": 1, + fullSalesSquare: { + $pow: ["$sales.revenue", 2] + } + } +}]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "sales": { + "revenue": 279183 + }, + "company": "First Up Consultants", + "salesVolumeDoubled": 558366 + }, + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "sales": { + "revenue": 50000 + }, + "company": "First Up Consultants", + "salesVolumeDoubled": 100000 + }, + { + "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad", + "sales": { + "revenue": 68508 + }, + "company": "First Up Consultants", + "salesVolumeDoubled": 137016 + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$round.md b/api-reference/operators/arithmetic-expression/$round.md new file mode 100644 index 0000000..cdd4421 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$round.md @@ -0,0 +1,249 @@ +--- +title: $round +description: The $round operator rounds a number to a specified decimal place. +type: operators +category: arithmetic-expression +--- + +# $round + +The `$round` operator is used to round a number to a specified decimal place. It's useful in aggregations where numerical precision is important, such as financial calculations or statistical analysis. + +## Syntax + +```javascript +{ + $round: [ , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The number to be rounded. | +| **``** | The decimal place to which the number should be rounded. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Round the location coordinates of stores + +To round the latitude and longitude of all stores within the "First Up Consultants" company, first run a query to filter on the name of the company. Then, use the $round operator on the lat and lon fields to return the desired result. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $project: { + company: 1, + "location.lat": 1, + "location.lon": 1, + roundedLat: { + $round: ["$location.lat", 1] + }, + roundedLon: { + $round: ["$location.lon", 1] + } + } +}]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "location": { + "lat": 87.2239, + "lon": -129.0506 + }, + "company": "First Up Consultants", + "roundedLat": 87.2, + "roundedLon": -129.1 + }, + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "location": { + "lat": -29.1866, + "lon": -112.7858 + }, + "company": "First Up Consultants", + "roundedLat": -29.2, + "roundedLon": -112.8 + }, + { + "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad", + "location": { + "lat": -0.2136, + "lon": 108.7466 + }, + "company": "First Up Consultants", + "roundedLat": -0.2, + "roundedLon": 108.7 + } +] +``` + +### Example 2 - Round to the nearest thousand + +To round the total sales volume of stores within the "First Up Consultants" company, first run a query to filter stores by the company name. Then use the $round operator on the totalSales field to round the value to the nearest thousand. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $project: { + company: 1, + "sales.totalSales": 1, + roundedSales: { + $round: ["$sales.totalSales", -3] + } + } +}]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "sales": {}, + "company": "First Up Consultants", + "roundedSales": 279000 + }, + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "sales": {}, + "company": "First Up Consultants", + "roundedSales": 50000 + }, + { + "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad", + "sales": {}, + "company": "First Up Consultants", + "roundedSales": 69000 + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$sqrt.md b/api-reference/operators/arithmetic-expression/$sqrt.md new file mode 100644 index 0000000..2357349 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$sqrt.md @@ -0,0 +1,220 @@ +--- +title: $sqrt +description: The $sqrt operator calculates and returns the square root of an input number +type: operators +category: arithmetic-expression +--- + +# $sqrt + +The `$sqrt` operator is used to calculate the square root of a specified number. + +## Syntax + +```javascript +{ + $sqrt: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| Any valid expression that resolves to a number. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculate the square root of sales + +To calculate the square root of the sales volumes of each store under the "First Up Consultants" company, first run a query to filter stores by the company name. Then, use the $sqrt operator on the totalSales field to retrieve the desired results. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $project: { + name: 1, + "sales.revenue": 1, + categoryName: "$promotionEvents.discounts.categoryName", + sqrtFullSales: { + $sqrt: "$sales.revenue" + } + } +}]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "c52c9f65-5b1a-4ef5-a7a2-d1af0426cbe4", + "name": "First Up Consultants | Jewelry Pantry - Nicolasberg", + "sales": { + "revenue": 4624 + }, + "categoryName": [ + [ + "Watches", + "Bracelets" + ], + [ + "Brooches", + "Necklaces" + ], + [ + "Charms", + "Brooches" + ], + [ + "Brooches", + "Anklets" + ], + [ + "Earrings", + "Anklets" + ] + ], + "sqrtFullSales": 68 + }, + { + "_id": "176aa484-c21c-44ce-ab6d-5e097bbdc2b4", + "name": "First Up Consultants | Medical Supply Shop - Daughertyville", + "sales": { + "revenue": 67311 + }, + "categoryName": [ + [ + "First Aid Kits", + "OTC Medications" + ], + [ + "Blood Pressure Monitors", + "OTC Medications" + ], + [ + "Face Masks", + "Stethoscopes" + ] + ], + "sqrtFullSales": 259.44363549719236 + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$subtract.md b/api-reference/operators/arithmetic-expression/$subtract.md new file mode 100644 index 0000000..d271085 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$subtract.md @@ -0,0 +1,203 @@ +--- +title: $subtract +description: The $subtract operator subtracts two numbers and returns the result. +type: operators +category: arithmetic-expression +--- + +# $subtract + +The `$subtract` operator is used to subtract two numbers and return the result. + +## Syntax + +```javascript +{ + $subtract: [ , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The minuend (the number from which another number is to be subtracted). | +| **``** | The subtrahend (the number to be subtracted). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculating the difference between full time and part time staff + +To calculate the absolute difference in part time and full time staff for stores within the "First Up Consultants" company, first run a query to filter stores by the company name. Then, use the $diff operator along with the $abs operator to calculate the absolute difference between the full time and part time staff for each store. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $project: { + name: 1, + staff: 1, + staffCountDiff: { + $abs: { + $subtract: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] + } + } + } +}]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad", + "name": "First Up Consultants | Plumbing Supply Shoppe - New Ubaldofort", + "staff": { + "employeeCount": { + "fullTime": 20, + "partTime": 18 + } + }, + "staffCountDiff": 2 + }, + { + "_id": "bfb213fa-8db8-419f-8e5b-e7096120bad2", + "name": "First Up Consultants | Beauty Product Shop - Hansenton", + "staff": { + "employeeCount": { + "fullTime": 18, + "partTime": 10 + } + }, + "staffCountDiff": 8 + }, + { + "_id": "14ab145b-0819-4d22-9e02-9ae0725fcda9", + "name": "First Up Consultants | Flooring Haven - Otisville", + "staff": { + "employeeCount": { + "fullTime": 19, + "partTime": 10 + } + }, + "staffCountDiff": 9 + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/$trunc.md b/api-reference/operators/arithmetic-expression/$trunc.md new file mode 100644 index 0000000..9016535 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/$trunc.md @@ -0,0 +1,190 @@ +--- +title: $trunc +description: The $trunc operator truncates a number to a specified decimal place. +type: operators +category: arithmetic-expression +--- + +# $trunc + +The `$trunc` operator truncates a number to a specified decimal place. + +## Syntax + +```javascript +{ + $trunc: [ , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The number to truncate. | +| **``** | The decimal place to truncate the specified number to. A positive value truncates to the right of the decimal point, and a negative value truncates to the left of the decimal point. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Fetch truncated location coordinates + +To retrieve the truncated coordinates of stores within the "First Up Consultants" company, first run a query to filter stores by the company name. Then, use the $trunc operator on the latitude and longitude fields to return the desired result. + +```javascript +db.stores.aggregate([ + { + $project: { + truncatedLat: { $trunc: ["$location.lat", 2] } + } + } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "name": "First Up Consultants | Bed and Bath Pantry - Port Antone", + "location": { + "lat": 87.2239, + "lon": -129.0506 + }, + "truncatedLatitute": 87, + "truncatedLongitude": -129 + }, + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "location": { + "lat": -29.1866, + "lon": -112.7858 + }, + "truncatedLatitute": -29, + "truncatedLongitude": -112 + }, + { + "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad", + "name": "First Up Consultants | Plumbing Supply Shoppe - New Ubaldofort", + "location": { + "lat": -0.2136, + "lon": 108.7466 + }, + "truncatedLatitute": 0, + "truncatedLongitude": 108 + } +] +``` diff --git a/api-reference/operators/arithmetic-expression/index.md b/api-reference/operators/arithmetic-expression/index.md new file mode 100644 index 0000000..c44c4a7 --- /dev/null +++ b/api-reference/operators/arithmetic-expression/index.md @@ -0,0 +1,16 @@ +# Arithmetic Expressions + +This section contains documentation for arithmetic expression operators. + +## Overview + +Arithmetic expression operators perform mathematical operations on numeric values. + +## Available Operators + +*More content to be added as operators are documented.* + +## Related Topics + +- [Comparison Operators](../comparison/) +- [Bitwise Operators](../bitwise/) diff --git a/api-reference/operators/array-expression/$arrayelemat.md b/api-reference/operators/array-expression/$arrayelemat.md new file mode 100644 index 0000000..201aabe --- /dev/null +++ b/api-reference/operators/array-expression/$arrayelemat.md @@ -0,0 +1,179 @@ +--- +title: $arrayElemAt +description: The $arrayElemAt returns the element at the specified array index. +type: operators +category: array-expression +--- + +# $arrayElemAt + +The `$arrayElemAt` operator is used to return the element at the specified array index. This operator is helpful when you need to extract a specific element from an array within your documents. + +## Syntax + +```javascript +{ + $arrayElemAt: ["", ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The array reference from which the element is retrieved.| +| **``**| The index of the element to return. The index is zero-based. A negative index counts from the end of the array.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Cables", + "totalSales": 1000 + }, + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Cyber Monday Event", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 8, + "Day": 1 + }, + "endDate": { + "Year": 2024, + "Month": 8, + "Day": 7 + } + }, + "discounts": [ + { + "categoryName": "DJ Speakers", + "discountPercentage": 25 + } + ] + }, + { + "eventName": "Black Friday Event", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 8, + "Day": 1 + }, + "endDate": { + "Year": 2024, + "Month": 8, + "Day": 7 + } + }, + "discounts": [ + { + "categoryName": "DJ Speakers", + "discountPercentage": 25 + } + ] + }, + { + "eventName": "Mega Discount Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 5, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 5, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Lights", + "discountPercentage": 20 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#NewArrival", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} + +``` + +### Example 1: Return the first element from an array field + +This query retrieves the first event details from `promotionEvents` array for the searched store. + +```javascript +db.stores.aggregate([ + { $match: { name: "Lakeshore Retail | DJ Equipment Stop - Port Cecile" } }, + { + $project: { + firstPromotionEvent: { $arrayElemAt: ["$promotionEvents", 0] } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "firstPromotionEvent": { + "eventName": "Cyber Monday Event", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 8, + "Day": 1 + }, + "endDate": { + "Year": 2024, + "Month": 8, + "Day": 7 + } + }, + "discounts": [ + { + "categoryName": "DJ Speakers", + "discountPercentage": 25 + } + ] + } + } +] +``` diff --git a/api-reference/operators/array-expression/$arraytoobject.md b/api-reference/operators/array-expression/$arraytoobject.md new file mode 100644 index 0000000..602bedb --- /dev/null +++ b/api-reference/operators/array-expression/$arraytoobject.md @@ -0,0 +1,152 @@ +--- +title: $arrayToObject +description: The $arrayToObject allows converting an array into a single document. +type: operators +category: array-expression +--- + +# $arrayToObject + +The `$arrayToObject` operator is used to convert an array into a single document. This operator is useful when you need to transform arrays of key-value pairs into a more structured document format. + +## Syntax + +```javascript +{ + $arrayToObject: "" +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The array to be converted into a document. Each element in the array must be either: a) A two-element array where the first element is the field name and the second element is the field value. b) A document with exactly two fields, "k" and "v", where "k" is the field name and "v" is the field value.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + }, + { + "categoryName": "DJ Cables", + "totalSales": 1000 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + }, + { + "eventName": "Discount Delight Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 5, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 5, + "Day": 18 + } + } + } + ], + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Convert the array to a key: value document + +This query converts the `salesByCategory` array into an object where each `categoryName` is a key and `totalSales` is the corresponding value. This transformation simplifies access to sales data by category directly from an object structure. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" + } + }, + { + $project: { + "sales.salesByCategory": { + $arrayToObject: { + $map: { + input: "$sales.salesByCategory", + as: "item", + in: { + k: "$$item.categoryName", + v: "$$item.totalSales" + } + } + } + } + } + } +]) +``` + +The query returns the following result. + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "sales": { + "salesByCategory": { + "DJ Headphones": 35921, + "DJ Cables": 1000 + } + } + } +] +``` diff --git a/api-reference/operators/array-expression/$concatarrays.md b/api-reference/operators/array-expression/$concatarrays.md new file mode 100644 index 0000000..c37408b --- /dev/null +++ b/api-reference/operators/array-expression/$concatarrays.md @@ -0,0 +1,136 @@ +--- +title: $concatArrays +description: The $concatArrays is used to combine multiple arrays into a single array. +type: operators +category: array-expression +--- + +# $concatArrays + +The `$concatArrays` operator is used to combine multiple arrays into a single array. This operator is useful when you need to merge arrays from different documents or fields in a document. + +## Syntax + +```javascript +{ + $concatArrays: ["", ""] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`, `**| The array fields targeted for concatenation.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + }, + { + "categoryName": "DJ Cables", + "totalSales": 1000 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + }, + { + "eventName": "Discount Delight Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 5, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 5, + "Day": 18 + } + } + } + ], + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Concatenating Arrays in a document + +This query merges the `categoryName` field from the `promotionEvents.discounts` array with the `tag` array into a single combinedTags array. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" + } +}, { + $project: { + combinedTags: { + $concatArrays: ["$promotionEvents.discounts.categoryName", "$tag"] + } + } +}]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "combinedTags": [ '#ShopLocal', '#NewArrival', '#NewArrival', '#FreeShipping' ] + } +] +``` diff --git a/api-reference/operators/array-expression/$filter.md b/api-reference/operators/array-expression/$filter.md new file mode 100644 index 0000000..c7cab69 --- /dev/null +++ b/api-reference/operators/array-expression/$filter.md @@ -0,0 +1,155 @@ +--- +title: $filter +description: The $filter operator filters for elements from an array based on a specified condition. +type: operators +category: array-expression +--- + +# $filter + +The `$filter` operator is used to filter elements from an array based on a specified condition. This operator is useful when you need to manipulate or retrieve specific array elements within documents. + +## Syntax + +```javascript +{ + $filter: { + input: "", + as: "", + cond: "" + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`**| An expression that resolves to an array.| +| **`as`**| A string that specifies the variable name for each element in the input array.| +| **`cond`**| An expression that determines whether to include the element in the output array.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + }, + { + "categoryName": "DJ Cables", + "totalSales": 1000 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + }, + { + "eventName": "Discount Delight Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 5, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 5, + "Day": 18 + } + } + } + ], + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Retrieve an element filtered on condition + +This query demonstrates how to filter sales category based on `totalSales`. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" + } + }, + { + $project: { + filteredSalesByCategory: { + $filter: { + input: "$sales.salesByCategory", + as: "item", + cond: { + $gt: ["$$item.totalSales", 10000] + } + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "filteredSalesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ] + } +] +``` diff --git a/api-reference/operators/array-expression/$indexofarray.md b/api-reference/operators/array-expression/$indexofarray.md new file mode 100644 index 0000000..39ad134 --- /dev/null +++ b/api-reference/operators/array-expression/$indexofarray.md @@ -0,0 +1,179 @@ +--- +title: $indexOfArray +description: The $indexOfArray operator is used to search for an element in an array and return the index of the first occurrence of the element. +type: operators +category: array-expression +--- + +# $indexOfArray + +The `$indexOfArray` operator is used to search for an element in an array and return the index of the first occurrence of the element. If the element isn't found, it returns `-1`. This operator is useful for queries where you need to determine the position of an element within an array. For example, finding the index of a specific value or object in a list. + +## Syntax + +```javascript +{ + $indexOfArray: [ < array > , < searchElement > , < start > , < end > ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The array in which you want to search for the element.| +| **``**| The element you're searching for in the array.| +| **``**| (Optional) The index from which to start the search. If omitted, the search starts from the beginning of the array.| +| **``**| (Optional) The index at which to end the search. If omitted, the search goes until the end of the array.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Finding the index of the first occurrence + +This query finds the position (index) of a specific category name ("DJ Headphones") inside the `salesByCategory` array across the collection. + +```javascript +db.stores.aggregate([ + { + $project: { + index: { + $indexOfArray: [ + "$sales.salesByCategory.categoryName", + "DJ Headphones" + ] + } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41", + "index": -1 + }, + { + "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34", + "index": -1 + }, + { + "_id": "57cc4095-77d9-4345-af20-f8ead9ef0197", + "index": -1 + } +] +``` + +### Example 2: Finding the index in a range + +This query finds the position of the "Bargain Blitz Days" promotion event inside the `promotionEvents` array within a specific range of indexes (3 to 5) and filters results along with returning the first three matching documents + +```javascript +db.stores.aggregate([ + // Step 1: Project the index of the "Bargain Blitz Days" event name within the specified range + { + $project: { + index: { + $indexOfArray: [ + "$promotionEvents.eventName", + "Bargain Blitz Days", + 3, + 5 + ] + } + } + }, + // Step 2: Match documents where index > 0 + { + $match: { + index: { $gt: 0 } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 } +]) +``` + +This query returns the following results: + +```json + [ + { + "_id": "ced8caf0-051a-48ce-88d3-2935815261c3", + "index": 3 + }, + { + "_id": "509be7ce-539a-41b5-8fde-b85fb3ef3faa", + "index": 3 + }, + { + "_id": "d06e8136-9a7f-4b08-92c8-dc8eac73bad3", + "index": 3 + } +] +``` diff --git a/api-reference/operators/array-expression/$isarray.md b/api-reference/operators/array-expression/$isarray.md new file mode 100644 index 0000000..5253b8f --- /dev/null +++ b/api-reference/operators/array-expression/$isarray.md @@ -0,0 +1,160 @@ +--- +title: $isArray +description: The $isArray operator is used to determine if a specified value is an array. +type: operators +category: array-expression +--- + +# $isArray + +The `$isArray` operator is used to determine if a specified value is an array. It returns `true` if the value is an array and `false` otherwise. This operator is often used in aggregation pipelines to filter or transform documents based on whether a field contains an array. + +## Syntax + +```javascript +{ + $isArray: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| Any valid expression that resolves to a value you want to check.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Checking if a field is an array + +This query checks whether the `sales.salesByCategory` field in each store document is an array and returns that information for the first three documents. + +```javascript +db.stores.aggregate([ + { + $project: { + _id: 1, + isSalesByCategoryArray: { $isArray: "$sales.salesByCategory" } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41", + "isSalesByCategoryArray": true + }, + { + "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34", + "isSalesByCategoryArray": true + }, + { + "_id": "57cc4095-77d9-4345-af20-f8ead9ef0197", + "isSalesByCategoryArray": true + } +] +``` + +### Example 2: Filtering documents based on array fields + +This query demonstrates use of `$isArray` to filter documents where the `promotionEvents` field is an array. + +```javascript +db.stores.aggregate([ + { + $match: { + $expr: { $isArray: "$promotionEvents" } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 }, + // Include only _id and name fields in the output + { $project: { _id: 1, name: 1 } } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41", + "name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie" + }, + { + "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34", + "name": "Northwind Traders | Bed and Bath Place - West Oraland" + }, + { + "_id": "57cc4095-77d9-4345-af20-f8ead9ef0197", + "name": "Wide World Importers | Bed and Bath Store - West Vitafort" + } +] +``` diff --git a/api-reference/operators/array-expression/$map.md b/api-reference/operators/array-expression/$map.md new file mode 100644 index 0000000..8f3ca40 --- /dev/null +++ b/api-reference/operators/array-expression/$map.md @@ -0,0 +1,136 @@ +--- +title: $map +description: The $map operator allows applying an expression to each element in an array. +type: operators +category: array-expression +--- + +# $map + +The `$map` operator is used to apply an expression to each element in an array and return an array with the applied results. This operator is useful for transforming arrays within documents, such as modifying each element or extracting specific fields. + +## Syntax + +```javascript +{ + $map: { + input: , + as: , + in: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The array processed by the expression. | +| **`as`** | The variable name for each element in the array. | +| **`in`** | The expression to apply to each element. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60", + "name": "Lakeshore Retail", + "location": { + "lat": -51.3041, + "lon": -166.0838 + }, + "staff": { + "totalStaff": { + "fullTime": 5, + "partTime": 20 + } + }, + "sales": { + "totalSales": 266491, + "salesByCategory": [ + { + "categoryName": "Towel Racks", + "totalSales": 13237 + }, + { + "categoryName": "Washcloths", + "totalSales": 44315 + }, + { + "categoryName": "Face Towels", + "totalSales": 42095 + }, + { + "categoryName": "Toothbrush Holders", + "totalSales": 47912 + }, + { + "categoryName": "Hybrid Mattresses", + "totalSales": 48660 + }, + { + "categoryName": "Napkins", + "totalSales": 31439 + }, + { + "categoryName": "Pillow Cases", + "totalSales": 38833 + } + ] + }, + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Extracting category names + +This query filters the `stores` collection for `_id`, then projects a new field `categoryNames` where each element in the salesByCategory array has its totalSales increased by 500 using the $map operator. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "988d2dd1-2faa-4072-b420-b91b95cbfd60" + } + }, + { + $project: { + categoryNames: { + $map: { + input: "$sales.salesByCategory.totalSales", + as: "category", + in: { + $add: ["$$category", 500] + } + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60", + "categoryNames": [ + 13737, + 44815, + 42595, + 48412, + 49160, + 31939, + 39333 + ] + } +] +``` diff --git a/api-reference/operators/array-expression/$range.md b/api-reference/operators/array-expression/$range.md new file mode 100644 index 0000000..b74f34c --- /dev/null +++ b/api-reference/operators/array-expression/$range.md @@ -0,0 +1,209 @@ +--- +title: $range +description: The $range operator allows generating an array of sequential integers. +type: operators +category: array-expression +--- + +# $range + +The `$range` operator is used to generate an array of sequential integers. The operator helps create number arrays in a range, useful for pagination, indexing, or test data. + +## Syntax + +```javascript +{ + $range: [ , , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`start`** | The starting value of the range (inclusive). | +| **`end`** | The ending value of the range (exclusive). | +| **`step`** | The increment value between each number in the range (optional, defaults to 1). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Generate a range of numbers + +This query demonstrates usage of operator to generate an array of integers from 0 to 5, wherein it includes the left boundary while excludes the right. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6" + } +}, { + $project: { + rangeArray: { + $range: [0, 5] + } + } +}]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "rangeArray": [ + 0, + 1, + 2, + 3, + 4 + ] + } +] +``` + +### Example 2: Generate a range of numbers with a step value + +This query demonstrates usage of operator to generate an array of even numbers from 0 to 18. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6" + } +}, { + $project: { + evenNumbers: { + $range: [0, 8, 2] + } + } +}]) +``` + +This query results the following result. + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "rangeArray": [ + 0, + 2, + 4, + 6 + ] + } +] +``` diff --git a/api-reference/operators/array-expression/$reduce.md b/api-reference/operators/array-expression/$reduce.md new file mode 100644 index 0000000..cb16629 --- /dev/null +++ b/api-reference/operators/array-expression/$reduce.md @@ -0,0 +1,177 @@ +--- +title: $reduce +description: The $reduce operator applies an expression to each element in an array & accumulate result as single value. +type: operators +category: array-expression +--- + +# $reduce + +The `$reduce` operator is used to apply an expression to each element in an array and accumulate the results into a single value. This operator is useful for performing operations that require iterating over array elements and aggregating their values. + +## Syntax + +```javascript +$reduce: { + input: , + initialValue: , + in: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The array to iterate over. | +| **`initialValue`** | The initial cumulative value set before the array iteration begins. | +| **`in`** | A valid expression that evaluates to the accumulated value for each element in the array. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Aggregates the array values + +This query demonstrates how to use `$reduce` to sum the total sales across different categories in the `salesByCategory` array. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "988d2dd1-2faa-4072-b420-b91b95cbfd60" + } +}, { + $project: { + totalSalesByCategory: { + $reduce: { + input: "$sales.salesByCategory.totalSales", + initialValue: 0, + in: { + $add: ["$$value", "$$this"] + } + } + } + } +}]) +``` + +The query returns the following result. + +```json +[ + { + "_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60", + "totalSalesByCategory": 149849 + } +] +``` diff --git a/api-reference/operators/array-expression/$reversearray.md b/api-reference/operators/array-expression/$reversearray.md new file mode 100644 index 0000000..14fdea6 --- /dev/null +++ b/api-reference/operators/array-expression/$reversearray.md @@ -0,0 +1,179 @@ +--- +title: $reverseArray +description: The $reverseArray operator is used to reverse the order of elements in an array. +type: operators +category: array-expression +--- + +# $reverseArray + +The `$reverseArray` operator is used to reverse the order of elements in an array. This operator can be useful when you need to process or display array elements in the opposite order. It's an array expression operator and can be used within aggregation pipelines. + +## Syntax + +```javascript +{ + $reverseArray: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The array that you want to reverse.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + }, + { + "eventName": "Discount Delight Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 5, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 5, + "Day": 18 + } + } + } + ], + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` + +### Example 1: Reversing the order of an array + +This query demonstrates the usage of operator for performing reversal on the order of the `promotionEvents` array. + +```javascript +db.stores.aggregate([ + //filtering to one document + { + $match: { + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" + } + }, + { + $project: { + _id: 1, + name: 1, + promotionEventsReversed: { + $reverseArray: "$promotionEvents" + } + } + }, + // Include only _id, name, promotionalDates and eventName fields in the output + { + $project: { + _id: 1, + name: 1, + "promotionEventsReversed.promotionalDates": 1, + "promotionEventsReversed.eventName": 1 + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "promotionEventsReversed": [ + { + "eventName": "Discount Delight Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 5, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 5, + "Day": 18 + } + } + }, + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + } + } + ] + } +] +``` diff --git a/api-reference/operators/array-expression/$slice.md b/api-reference/operators/array-expression/$slice.md new file mode 100644 index 0000000..b5bb901 --- /dev/null +++ b/api-reference/operators/array-expression/$slice.md @@ -0,0 +1,466 @@ +--- +title: $slice +description: The $slice operator returns a subset of an array from any element onwards in the array. +type: operators +category: array-expression +--- + +# $slice + +The `$slice` operator is used to return a subset of an array. It can be used to limit the number of elements in an array to a specified number or to return elements from a specified position in the array. The operator is useful when dealing with large arrays where only a portion of the data is needed for processing or display. + +## Syntax + +The syntax for the `$slice` operator is as following. + +- Returns elements from either the start or end of the array + +```javascript +{ + $slice: [ , ] +} +``` + +- Returns elements from the specified position in the array + +```javascript +{ + $slice: [ , , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`array`** | Any valid array expression. | +| **`position`** | Any valid integer expression. | +| **`n`** | Any valid integer expression. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Return the set of elements from the array + +This query retrieves the first three elements of the `sales.salesByCategory` array for `_id: 988d2dd1-2faa-4072-b420-b91b95cbfd60` within `stores` collection. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "988d2dd1-2faa-4072-b420-b91b95cbfd60" + } +}, { + $project: { + salesByCategory: { + $slice: ["$sales.salesByCategory", 3] + } + } +}]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60", + "salesByCategory": [ + { + "categoryName": "Towel Racks", + "totalSales": 13237 + }, + { + "categoryName": "Washcloths", + "totalSales": 44315 + }, + { + "categoryName": "Face Towels", + "totalSales": 42095 + } + ] + } +] +``` + +### Example 2: Slice with $push + +This query uses `$push` with `$each` to add new elements to the `promotionEvents` array and `$slice` to retain only the first N (positive slice) or last N (negative slice) elements. This ensures the array keeps the most recent entries after the update. + +```javascript +db.stores.updateOne({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" +}, { + $push: { + promotionEvents: { + $each: [{ + eventName: "Black Friday Event", + promotionalDates: { + startDate: { + Year: 2024, + Month: 8, + Day: 1 + }, + endDate: { + Year: 2024, + Month: 8, + Day: 7 + } + }, + discounts: [{ + categoryName: 'DJ Speakers', + discountPercentage: 25 + }] + }, + { + eventName: "Mega Discount Days", + promotionalDates: { + startDate: { + Year: 2024, + Month: 5, + Day: 11 + }, + endDate: { + Year: 2024, + Month: 5, + Day: 18 + } + }, + discounts: [{ + categoryName: "DJ Lights", + discountPercentage: 20 + }] + } + ], + $slice: -3 + } + } +}) +``` + +The query returns the following result. + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + }, + { + "categoryName": "DJ Cables", + "totalSales": 1000 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Cyber Monday Event", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 8, + "Day": 1 + }, + "endDate": { + "Year": 2024, + "Month": 8, + "Day": 7 + } + }, + "discounts": [ + { + "categoryName": "DJ Speakers", + "discountPercentage": 25 + } + ] + }, + { + "eventName": "Black Friday Event", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 8, + "Day": 1 + }, + "endDate": { + "Year": 2024, + "Month": 8, + "Day": 7 + } + }, + "discounts": [ + { + "categoryName": "DJ Speakers", + "discountPercentage": 25 + } + ] + }, + { + "eventName": "Mega Discount Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 5, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 5, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Lights", + "discountPercentage": 20 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#NewArrival", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] + } +] +``` + +### Example 3: Fetch the first matching element from an array + +This query retrieves the first document from "sales.salesByCategory" array. + +```javascript +db.stores.find({ + name: "Lakeshore Retail" + }, { + _id: 1, + name: 1, + "sales.salesByCategory": { + $slice: 1 + } + } // restricts the fields to be returned +) +``` + +This query returns the following result. + +```json +[ + { + "_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60", + "name": "Lakeshore Retail", + "sales": { + "salesByCategory": [ + { + "categoryName": "Towel Racks", + "totalSales": 13237 + } + ] + } + } +] +``` + +### Example 4: Fetch the last element from an array + +This query retrieves the last document from "sales.salesByCategory" array. + +```javascript +db.stores.find({ + name: "Lakeshore Retail" +}, { + _id: 1, + name: 1, + "sales.salesByCategory": { + $slice: -1 + } +}) +``` + +This query returns the following result. + +```json +[ + { + "_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60", + "name": "Lakeshore Retail", + "sales": { + "salesByCategory": [ + { + "categoryName": "Pillow Cases", + "totalSales": 38833 + } + ] + } + } +] +``` + +### Example 5: Retrieve a range of elements from an array + +This query retrieves a subset range from "sales.salesByCategory" array. + +```javascript +db.stores.find({ + name: "Lakeshore Retail" +}, { + _id: 1, + name: 1, + "sales.salesByCategory": { + $slice: [3, 2] + } +}) +``` + +This query returns the following result. + +```json +[ + { + "_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60", + "name": "Lakeshore Retail", + "sales": { + "salesByCategory": [ + { + "categoryName": "Toothbrush Holders", + "totalSales": 47912 + }, + { + "categoryName": "Hybrid Mattresses", + "totalSales": 48660 + } + ] + } + } +] +``` diff --git a/api-reference/operators/array-expression/$sortarray.md b/api-reference/operators/array-expression/$sortarray.md new file mode 100644 index 0000000..15be7c3 --- /dev/null +++ b/api-reference/operators/array-expression/$sortarray.md @@ -0,0 +1,193 @@ +--- +title: $sortArray +description: The $sortArray operator helps in sorting the elements in an array. +type: operators +category: array-expression +--- + +# $sortArray + +The `$sortArray` operator is used to sort the elements of an array. The operator can be useful when you need to sort arrays within your documents based on specific fields or criteria. It can be applied to arrays of embedded documents or simple arrays of values. + +## Syntax + +```javascript +{ + $sortArray: { + input: , + sortBy: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The array to be sorted. | +| **`sortBy`** | Specifies the sort order. It can be a single field or multiple fields with their corresponding sort order (1 for ascending, -1 for descending). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Sorting an Array of Embedded Documents + +This query sorts the `sales.salesByCategory` array within each document in descending order based on `totalSales`. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "d3c9df51-41bd-4b4e-a26b-b038d9cf8b45" + } +}, { + $project: { + sortedSalesByCategory: { + $sortArray: { + input: "$sales.salesByCategory", + sortBy: { + totalSales: -1 + } + } + } + } +}]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "d3c9df51-41bd-4b4e-a26b-b038d9cf8b45", + "sortedSalesByCategory": [ + { + "categoryName": "DJ Accessories", + "totalSales": 60000 + }, + { + "categoryName": "Music Accessories", + "totalSales": 40000 + }, + { + "categoryName": "DJ Speakers", + "totalSales": 36972 + }, + { + "categoryName": "DJ Headphones", + "totalSales": 12877 + } + ] + } +] +``` diff --git a/api-reference/operators/array-expression/$zip.md b/api-reference/operators/array-expression/$zip.md new file mode 100644 index 0000000..19673d2 --- /dev/null +++ b/api-reference/operators/array-expression/$zip.md @@ -0,0 +1,184 @@ +--- +title: $zip +description: The $zip operator allows merging two or more arrays element-wise into a single array or arrays. +type: operators +category: array-expression +--- + +# $zip + +The `$zip` operator is used to merge two or more arrays element-wise into a single array of arrays. It's useful when you want to combine related elements from multiple arrays into a single array structure. + +## Syntax + +```javascript +{ + $zip: { + inputs: [ , , ... ], + useLongestLength: , // Optional + defaults: // Optional + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`inputs`** | An array of arrays to be merged element-wise. | +| **`useLongestLength`** | A boolean value that, if set to true, uses the longest length of the input arrays. If false or not specified, it uses the shortest length. | +| **`defaults`** | An array of default values to use if `useLongestLength` is true and any input array is shorter than the longest array. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic Usage + +Suppose you want to merge the `categoryName` and `totalSales` fields from the `salesByCategory` array. This query returns individual array of arrays under `categoryWithSales` field. `useLongestLength` set to `true` would return the following output, while a value of `false` removes the `Napkins` array from the output. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6" + } + }, + { + $project: { + name: 1, + categoryNames: "$sales.salesByCategory.categoryName", + totalSales: "$sales.salesByCategory.totalSales", + categoryWithSales: { + $zip: { + inputs: ["$sales.salesByCategory.categoryName", "$sales.salesByCategory.totalSales"], + useLongestLength: false + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "categoryNames": ["Stockings"], + "totalSales": [25731], + "categoryWithSales": [["Stockings", 25731]] + } +] +``` diff --git a/api-reference/operators/array-query/$all.md b/api-reference/operators/array-query/$all.md new file mode 100644 index 0000000..0bce6f9 --- /dev/null +++ b/api-reference/operators/array-query/$all.md @@ -0,0 +1,189 @@ +--- +title: $all +description: The $all operator helps finding array documents matching all the elements. +type: operators +category: array-query +--- + +# $all + +The `$all` operator is used to select documents where the value of a field is an array that contains all the specified elements. This operator is useful when you need to ensure that an array field contains multiple specified elements, regardless of their order in the array. + +## Syntax + +```javascript +db.collection.find({ + field : { + $all: [ < value1 > , < value2 > ] + } +}) +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to be queried. | +| **` , `** | The values that must all be present in the array field. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find documents containing all the specified elements in an array + +This query retrieves documents containing both elements `Laptops` and `Smartphones` within `salesByCategory.categoryName` array. + +```javascript +db.stores.find({ + "sales.salesByCategory.categoryName": { + $all: ["Laptops", "Smartphones"] + } +}, { + _id: 1, + "sales.salesByCategory.categoryName": 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "a57511bb-1ea3-4b26-bf0d-8bf928f2bfa8", + "sales": { + "salesByCategory": [ + { + "categoryName": "Smartphones" + }, + { + "categoryName": "Laptops" + } + ] + } + }, + { + "_id": "ca56d696-5208-40c3-aa04-d4e245df44dd", + "sales": { + "salesByCategory": [ + { + "categoryName": "Laptops" + }, + { + "categoryName": "Smartphones" + } + ] + } + } +] +``` diff --git a/api-reference/operators/array-query/$elemmatch.md b/api-reference/operators/array-query/$elemmatch.md new file mode 100644 index 0000000..b2ac106 --- /dev/null +++ b/api-reference/operators/array-query/$elemmatch.md @@ -0,0 +1,231 @@ +--- +title: $elemMatch +description: The $elemMatch operator returns complete array, qualifying criteria with at least one matching array element. +type: operators +category: array-query +--- + +# $elemMatch + +The `$elemMatch` operator is used to match documents that contain an array field with at least one element that matches all the specified query criteria. This operator is useful when you need to find array documents with specified element. + +## Syntax + +```javascript +db.collection.find({ : { $elemMatch: { , , ... } } }) +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field in the document that contains the array to be queried. | +| **`query`** | The conditions that at least one element in the array must satisfy. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find in an array for specific element among the list of elements + +This query retrieves the first two documents in the `stores` collection that have at least one discount with the category name "DJ Lighting" in their `promotionEvents` array. The query only returns the `_id` and `promotionEvents.discounts` fields for those documents. + +```javascript +db.stores.find({ + "promotionEvents.discounts": { + $elemMatch: { + categoryName: "DJ Lighting" + } + } +}, { + _id: 1, + "promotionEvents.discounts": 1 +}).limit(2) +``` + +This query returns the following results: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "promotionEvents": [ + { + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + }, + { + "discounts": [ + { + "categoryName": "DJ Lighting", + "discountPercentage": 14 + }, + { + "categoryName": "DJ Cases", + "discountPercentage": 20 + } + ] + } + ] + }, + { + "_id": "91de5201-8194-44bf-848f-674e8df8bf5e", + "promotionEvents": [ + { + "discounts": [ + { + "categoryName": "DJ Cases", + "discountPercentage": 6 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 14 + } + ] + }, + { + "discounts": [ + { + "categoryName": "DJ Headphones", + "discountPercentage": 19 + }, + { + "categoryName": "DJ Speakers", + "discountPercentage": 13 + } + ] + }, + { + "discounts": [ + { + "categoryName": "DJ Lighting", + "discountPercentage": 12 + }, + { + "categoryName": "DJ Accessories", + "discountPercentage": 6 + } + ] + } + ] + } +] +``` diff --git a/api-reference/operators/array-query/$size.md b/api-reference/operators/array-query/$size.md new file mode 100644 index 0000000..6554eb6 --- /dev/null +++ b/api-reference/operators/array-query/$size.md @@ -0,0 +1,232 @@ +--- +title: $size +description: The $size operator is used to query documents where an array field has a specified number of elements. +type: operators +category: array-query +--- + +# $size + +The `$size` operator is used to query documents where an array field has a specified number of elements. This operator is useful when you need to find documents based on the size of an array field, such as finding documents with some items in a list. + +## Syntax + +```javascript +db.collection.find({ : { $size: } }) +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field that contains the array. | +| **`number`** | The number of elements the array should have. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Finding documents with a specific number of elements in an array + +This query retrieves documents from the `stores` collection where the `sales.salesByCategory` array contains exactly seven items. + +```javascript +db.stores.find({ + "sales.salesByCategory": { + $size: 7 + } +}, { + _id: 1, + name: 1, + "sales.salesByCategory": 1 +}).limit(2) +``` + +This query returns the following results: + +```json +[ + { + "_id": "7ed4b356-1290-433e-bd96-bf95f817eaaa", + "name": "Wide World Importers", + "sales": { + "salesByCategory": [ + { + "categoryName": "Ultrabooks", + "totalSales": 31304 + }, + { + "categoryName": "Laptop Accessories", + "totalSales": 10044 + }, + { + "categoryName": "Laptops", + "totalSales": 48851 + }, + { + "categoryName": "Refill Kits", + "totalSales": 9604 + }, + { + "categoryName": "Prepaid Phones", + "totalSales": 28600 + }, + { + "categoryName": "Android Phones", + "totalSales": 4580 + }, + { + "categoryName": "Photo Printers", + "totalSales": 35234 + } + ] + } + }, + { + "_id": "988d2dd1-2faa-4072-b420-b91b95cbfd60", + "name": "Lakeshore Retail", + "sales": { + "salesByCategory": [ + { + "categoryName": "Towel Racks", + "totalSales": 13237 + }, + { + "categoryName": "Washcloths", + "totalSales": 44315 + }, + { + "categoryName": "Face Towels", + "totalSales": 42095 + }, + { + "categoryName": "Toothbrush Holders", + "totalSales": 47912 + }, + { + "categoryName": "Hybrid Mattresses", + "totalSales": 48660 + }, + { + "categoryName": "Napkins", + "totalSales": 31439 + }, + { + "categoryName": "Pillow Cases", + "totalSales": 38833 + } + ] + } + } +] +``` diff --git a/api-reference/operators/array-update/$.md b/api-reference/operators/array-update/$.md new file mode 100644 index 0000000..df5e6ba --- /dev/null +++ b/api-reference/operators/array-update/$.md @@ -0,0 +1,226 @@ +--- +title: $ +description: The $ positional operator identifies an element in an array to update without explicitly specifying the position of the element in the array. +type: operators +category: array-update +--- + +# $ + +The `$` positional operator identifies an element in an array to update without explicitly specifying the position of the element in the array. The `$` operator acts as a placeholder for the first element that matches the query condition, and the array field must appear as part of the query document. + +## Syntax + +```javascript +db.collection.updateOne( + { : }, + { : { ".$": } } +) +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`array`** | The array field that contains the element to update. Must be part of the query condition. | +| **`value`** | The value used to match the array element in the query condition. | +| **`update operator`** | The update operator to apply (for example, `$set`, `$inc`, `$unset`). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Project the first element of an array, matching the condition + +This query returns the first element within the `salesByCategory` array, for `DJ` equipment with `totalSales` greater than 35000. + +```javascript +db.stores.find({ + "sales.salesByCategory": { + $elemMatch: { + categoryName: { + $regex: "^DJ" + } + } + }, + "sales.salesByCategory.totalSales": { + $gt: 35000 + } +}, { + "sales.salesByCategory.$": 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "d3c9df51-41bd-4b4e-a26b-b038d9cf8b45", + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Speakers", + "totalSales": 36972 + } + ] + } + }, + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35911 + } + ] + } + } +] +``` + +### Example 2: Update discount percentage for a specific category + +This query updates the discount percentage for "Desks" category in the first matching promotion event. + +```javascript +db.stores.updateOne( + { + _id: "905d1939-e03a-413e-a9c4-221f74055aac", + "promotionEvents.discounts.categoryName": "Desks" + }, + { + $set: { "promotionEvents.$.discounts.$[elem].discountPercentage": 25 } + }, + { + arrayFilters: [{ "elem.categoryName": "Desks" }] + } +) +``` + +### Example 3: Update sales category total + +This query updates the total sales for a specific category using the `$ (positional operator)`. + +```javascript +db.stores.updateOne( + { + _id: "905d1939-e03a-413e-a9c4-221f74055aac", + "sales.salesByCategory.categoryName": "Desk Lamps" + }, + { + $inc: { "sales.salesByCategory.$.totalSales": 1000 } + } +) +``` diff --git a/api-reference/operators/array-update/$addtoset.md b/api-reference/operators/array-update/$addtoset.md new file mode 100644 index 0000000..8ffa0e5 --- /dev/null +++ b/api-reference/operators/array-update/$addtoset.md @@ -0,0 +1,282 @@ +--- +title: $addToSet +description: The addToSet operator adds elements to an array if they don't already exist, while ensuring uniqueness of elements within the set. +type: operators +category: array-update +--- + +# $addToSet + +The `$addToSet` operator adds elements to an array if they don't already exist, while ensuring uniqueness of elements within the set. + +## Syntax + +```javascript +{ + $addToSet: { : } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The field to which you want to add elements. | +| **``** | The value to be added to the array. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Add a new tag to the `tag` array + +This query adds a new tag to the array of tags, run a query using the $addToSet operator to add the new value. + +```javascript +db.stores.updateOne({ + _id: "0fcc0bf0-ed18-4ab8-b558-9848e18058f4" +}, { + $addToSet: { + tag: "#ShopLocal" + } +}) +``` + +This query returns the following result: + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "0", + "upsertedCount": 0 + } +] +``` + +### Example 2: Adding a new promotional event to the `promotionEvents` array + +This query adds a new event to the `promotionEvents` array, run a query using the $addToSet operator with the new promotion object to be added. + +```javascript +db.stores.updateOne({ + _id: "0fcc0bf0-ed18-4ab8-b558-9848e18058f4" +}, { + $addToSet: { + promotionEvents: { + eventName: "Summer Sale", + promotionalDates: { + startDate: { + Year: 2024, + Month: 6, + Day: 1 + }, + endDate: { + Year: 2024, + Month: 6, + Day: 15 + } + }, + discounts: [{ + categoryName: "DJ Speakers", + discountPercentage: 20 + }] + } + } +}) +``` + +This query returns the following result: + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] +``` + +### Example 3 - Using $addToSet with $setWindowOperators + +To retrieve the list of cities for each store within the "First Up Consultants" company, run a query to first partition stores by the company. Then, use the $addToSet operator to add the distinct cities for each store within the partition. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $setWindowFields: { + partitionBy: "$company", + sortBy: { + "sales.totalSales": -1 + }, + output: { + citiesForCompany: { + $push: "$city", + window: { + documents: ["unbounded", "current"] + } + } + } + } +}, { + $project: { + company: 1, + name: 1, + citiesForCompany: 1 + } +}]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "a1713bed-4c8b-46e7-bb68-259045dffdb4", + "name": "First Up Consultants | Bed and Bath Collection - Jaskolskiside", + "company": "First Up Consultants", + "citiesForCompany": [ + "South Thelma", + "South Carmenview", + "Port Antone", + "Charlotteville", + "South Lenorafort", + "Jaskolskiside" + ] + }, + { + "_id": "6b8585ab-4357-4da7-8625-f6a1cd5796c5", + "name": "First Up Consultants | Computer Depot - West Zack", + "company": "First Up Consultants", + "citiesForCompany": [ + "South Thelma", + "South Carmenview", + "Port Antone", + "Charlotteville", + "South Lenorafort", + "Jaskolskiside", + "West Zack" + ] + } +] +``` diff --git a/api-reference/operators/array-update/$each.md b/api-reference/operators/array-update/$each.md new file mode 100644 index 0000000..caba7e5 --- /dev/null +++ b/api-reference/operators/array-update/$each.md @@ -0,0 +1,198 @@ +--- +title: $each +description: The $each operator is used within an `$addToSet` or `$push` operation to add multiple elements to an array field in a single update operation. +type: operators +category: array-update +--- + +# $each + +The `$each` operator is used within an `$addToSet` or `$push` operation to add multiple elements to an array field in a single update operation. This operator is useful when you need to insert multiple items into an array without having to perform multiple update operations. The `$each` operator ensures that each item in the specified array is added to the target array. + +## Syntax + +```javascript +{ + $push: { + : { + $each: [ , ], + : , + : + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The field to be updated.| +| **`$each`**| An array of values to be added to the array field.| +| **``**| Optional modifiers like `$sort`, `$slice`, and `$position` to control the behavior of the `$push` operation.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Add multiple elements to an array + +This query adds multiple new promotion events to the `promotionEvents` array. + +```javascript +db.stores.updateOne({ + name: "Lenore's New DJ Equipment Store" +}, { + $push: { + promotionEvents: { + $each: [{ + eventName: "Grand Savings", + promotionalDates: { + startDate: "2024-08-01", + endDate: "2024-08-31" + }, + discounts: [{ + categoryName: "DJ Headphones", + discountPercentage: 5 + }] + }, + { + eventName: "Big Bargain", + promotionalDates: { + startDate: "2024-11-25", + endDate: "2024-11-30" + }, + discounts: [{ + categoryName: "DJ Headphones", + discountPercentage: 20 + }] + } + ] + } + } +}) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "0", + "modifiedCount": "0", + "upsertedCount": 0 + } +] +``` diff --git a/api-reference/operators/array-update/$pop.md b/api-reference/operators/array-update/$pop.md new file mode 100644 index 0000000..507872a --- /dev/null +++ b/api-reference/operators/array-update/$pop.md @@ -0,0 +1,198 @@ +--- +title: $pop +description: The $pop operator removes the first or last element of an array. +type: operators +category: array-update +--- + +# $pop + +The `$pop` operator is used to remove the first or last element of an array. This operator is useful when you need to manage arrays by removing elements from either end. The `$pop` operator can be used in update operations. + +## Syntax + +```javascript +{ + $pop: { + : + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The field that contains the array from which you want to remove an element. | +| **``** | Use `1` to remove the last element, and `-1` to remove the first element. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Remove the last element from an array + +To remove the last element from the tag array, run a query using the $pop operator on the tag field with a value of 1. + +```javascript +db.stores.update({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" +}, { + $pop: { + tag: 1 + } +}) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] + +``` + +### Example 2: Removing the first element from an array + +To remove the first element from the promotionEvents array, run a query using the $pop operator on the promotionEvents array with a value of -1. + +```javascript +db.stores.update({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" +}, { + $pop: { + promotionEvents: -1 + } +}) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] +``` diff --git a/api-reference/operators/array-update/$positional-all.md b/api-reference/operators/array-update/$positional-all.md new file mode 100644 index 0000000..2ef174c --- /dev/null +++ b/api-reference/operators/array-update/$positional-all.md @@ -0,0 +1,175 @@ +--- +title: $[] +description: The $[] operator is used to update all elements in an array that match the query condition. +type: operators +category: array-update +--- + +# $[] + +The $[] operator in DocumentDB is used to update all elements in an array that match a specified condition. This operator allows you to perform updates on multiple elements in an array without specifying their positions. It is particularly useful when you need to apply the same update to all items in an array. + +## Syntax + +```javascript +db.collection.update( + , + { + $set: { + .$[]: + } + } +) +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The selection criteria for the documents to update. | +| **``** | The field containing the array to update. | +| **``** | The value to set for each matching element in the array. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Updating Discount Percentages + +This query updates all elements in the discounts array inside each promotion event. + +```javascript +db.stores.updateOne( + { _id: "905d1939-e03a-413e-a9c4-221f74055aac" }, + { + $inc: { + "promotionEvents.$[].discounts.$[].discountPercentage": 5 + } + } +) +``` + +### Example 2: Updating Sales by Category + +This query increase the total sales for all categories by 10% by using the $[] operator. + +```javascript +db.stores.update( + { _id: "905d1939-e03a-413e-a9c4-221f74055aac" }, + { + $mul: { + "sales.salesByCategory.$[].totalSales": 1.10 + } + } +) +``` diff --git a/api-reference/operators/array-update/$positional-filtered.md b/api-reference/operators/array-update/$positional-filtered.md new file mode 100644 index 0000000..02db982 --- /dev/null +++ b/api-reference/operators/array-update/$positional-filtered.md @@ -0,0 +1,225 @@ +--- +title: $[] +description: The $[] operator is used to update all elements using a specific identifier in an array that match the query condition. +type: operators +category: array-update +--- + +# $[identifier] + +The $[identifier] array update operator is used to update specific elements in an array that match a given condition. This operator is useful when you need to update multiple elements within an array based on certain criteria. It allows for more granular updates within documents, making it a powerful tool for managing complex data structures. + +## Syntax + +```javascript +{ + : { + .$[]: + } +}, +{ + arrayFilters: [ + { .: } + ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The update operator to be applied (for example, `$set`, `$inc`, etc.). | +| **``** | The field containing the array to be updated. | +| **``** | A placeholder used in `arrayFilters` to match specific elements in the array. | +| **``** | The value to be set or updated. | +| **`arrayFilters`** | An array of filter conditions to identify which elements to update. | +| **``** | The specific field within array elements to be checked. | +| **``** | The condition that array elements must meet to be updated. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "location": { + "lat": -48.9752, + "lon": -141.6816 + }, + "staff": { + "employeeCount": { + "fullTime": 12, + "partTime": 19 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "Desk Lamps", + "totalSales": 37978 + } + ], + "revenue": 37978 + }, + "promotionEvents": [ + { + "eventName": "Crazy Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2023, + "Month": 9, + "Day": 27 + }, + "endDate": { + "Year": 2023, + "Month": 10, + "Day": 4 + } + }, + "discounts": [ + { + "categoryName": "Desks", + "discountPercentage": 25 + }, + { + "categoryName": "Filing Cabinets", + "discountPercentage": 23 + } + ] + }, + { + "eventName": "Incredible Markdown Mania", + "promotionalDates": { + "startDate": { + "Year": 2023, + "Month": 12, + "Day": 26 + }, + "endDate": { + "Year": 2024, + "Month": 1, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Monitor Stands", + "discountPercentage": 20 + }, + { + "categoryName": "Desks", + "discountPercentage": 24 + } + ] + }, + { + "eventName": "Major Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 25 + }, + "endDate": { + "Year": 2024, + "Month": 4, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Office Accessories", + "discountPercentage": 9 + }, + { + "categoryName": "Desks", + "discountPercentage": 13 + } + ] + }, + { + "eventName": "Blowout Bonanza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Office Chairs", + "discountPercentage": 24 + }, + { + "categoryName": "Desk Lamps", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Super Saver Fiesta", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 10, + "Day": 1 + } + }, + "discounts": [ + { + "categoryName": "Desks", + "discountPercentage": 5 + }, + { + "categoryName": "Monitor Stands", + "discountPercentage": 10 + } + ] + } + ], + "company": "Trey Research", + "city": "Lake Freeda", + "storeOpeningDate": "2024-12-30T22:55:25.779Z", + "lastUpdated": { + "t": 1729983325, + "i": 1 + } +} +``` + +### Example 1: Update the discount percentage for the chosen category in the specified promotion event. + +This query updates the discount percentage for the 'Desk Lamps' category by modifying the specific elements in the promotion event array where the event name is 'Blowout Bonanza'. + +```javascript +db.stores.updateOne( + { + _id: "905d1939-e03a-413e-a9c4-221f74055aac", + "promotionEvents.eventName": "Blowout Bonanza" + }, + { + $set: { + "promotionEvents.$[event].discounts.$[discount].discountPercentage": 18 + } + }, + { + arrayFilters: [ + { "event.eventName": "Blowout Bonanza" }, + { "discount.categoryName": "Desk Lamps" } + ] + } +) +``` diff --git a/api-reference/operators/array-update/$positional.md b/api-reference/operators/array-update/$positional.md new file mode 100644 index 0000000..34f7251 --- /dev/null +++ b/api-reference/operators/array-update/$positional.md @@ -0,0 +1,178 @@ +--- +title: $position +description: The $position is used to specify the position in the array where a new element should be inserted. +type: operators +category: array-update +--- + +# $position + +The `$position` operator is used to specify the position in the array where a new element should be inserted. This operator is useful when you need to insert an element at a specific index in an array rather than appending it to the end. + +## Syntax + +```javascript +{ + $push: { + : { + $each: [, ], + $position: + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The field in the document that contains the array to be updated.| +| **`, , ...`**| The values to be inserted into the array.| +| **``**| The position at which the values should be inserted.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Insert an element at specific index location in an array field + +This query inserts the tag `#NewArrival` at the second position (index 1) in the `tag` array of a specific document. + +```javascript +db.stores.update({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" +}, { + $push: { + tag: { + $each: ["#NewArrival"], + $position: 1 + } + } +}) +``` + +The updated document has the following values in the tag array. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "tag": [ + "#ShopLocal", + "#NewArrival", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} +``` diff --git a/api-reference/operators/array-update/$pull.md b/api-reference/operators/array-update/$pull.md new file mode 100644 index 0000000..aeb0c68 --- /dev/null +++ b/api-reference/operators/array-update/$pull.md @@ -0,0 +1,201 @@ +--- +title: $pull +description: Removes all instances of a value from an array. +type: operators +category: array-update +--- + +# $pull + +The `$pull` operator is used to remove all instances of a specified value or values that match a condition from an array. This is useful when you need to clean up or modify array data within your documents. + +## Syntax + +```javascript +{ + $pull: { : } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The field from which to remove one or more values. | +| **``** | The value or condition to remove from the array. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Remove a specific tag from the `tag` array + +To remove the value "#SeasonalSale" from the tag array field, run a query using the $pull operator on the tag field. + +```javascript +db.stores.update({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" +}, { + $pull: { + tag: "#SeasonalSale" + } +}) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] +``` + +### Example 2: Remove all events from the `promotionEvents` array that end before a certain date + +To remove all elements from the promotionEvents array where the endDate year is 2024 and the endDate month is earlier than March, run a query using the $pull operator on the promotionEvents field with the specified date values. + +```javascript +db.stores.update({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" + }, { + $pull: { + promotionEvents: { + "promotionalDates.endDate.Year": 2024, + "promotionalDates.endDate.Month": { + $lt: 3 + } + } + } + } +) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] +``` diff --git a/api-reference/operators/array-update/$pullall.md b/api-reference/operators/array-update/$pullall.md new file mode 100644 index 0000000..3c021be --- /dev/null +++ b/api-reference/operators/array-update/$pullall.md @@ -0,0 +1,171 @@ +--- +title: $pullAll +description: The $pullAll operator is used to remove all instances of the specified values from an array. +type: operators +category: array-update +--- + +# $pullAll + +The `$pullAll` operator is used to remove all instances of the specified values from an array. This operator is useful when you need to clean up arrays by removing multiple specific elements in a single operation. + +Both `$pull` and `$pullAll` are used to remove elements from an array, but they differ in how they identify the elements to be removed. `$pull` removes all elements from an array that match a specific condition, which can be a simple value or a more complex query (like matching sub-document fields). On the other hand, `$pullAll` removes specific values provided as an array of exact matches, but it doesn't support conditions or queries. Essentially, `$pull` is more flexible as it allows conditional removal based on various criteria, while `$pullAll` is simpler, working only with a fixed set of values. + +## Syntax + +```javascript +{ + $pullAll: { : [ , ] } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The field where the specified values will be removed.| +| **`[ , , ... ]`**| An array of values to be removed from the specified field.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Remove multiple elements from an array + +To remove the discounts for "#MembershipDeals" and "#SeasonalSale" from the 'tag' array, run a query using the $pulAll operator on the tag field with the values to remove. + +```javascript +db.stores.updateMany( + //filter + { _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"}, + { + $pullAll: { + tag: ["#MembershipDeals","#SeasonalSale" ] + } + } +) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": 1, + "modifiedCount": 1, + "upsertedCount": 0 + } +] +``` diff --git a/api-reference/operators/array-update/$push.md b/api-reference/operators/array-update/$push.md new file mode 100644 index 0000000..5881cd2 --- /dev/null +++ b/api-reference/operators/array-update/$push.md @@ -0,0 +1,243 @@ +--- +title: $push +description: The $push operator adds a specified value to an array within a document. +type: operators +category: array-update +--- + +# $push + +The `$push` operator is used to add a specified value to an array within a document. The $push operator adds new elements to an existing array without affecting other elements in the array. + +## Syntax + +```javascript +db.collection.update({ + < query > +}, { + $push: { + < field >: < value > + } +}, { + < options > +}) +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The selection criteria for the documents to update.| +| **``**| The array field to which the value will be appended.| +| **``**| The value to append to the array field.| +| **``**| Optional. Additional options for the update operation.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Add a new sales category + +To add a new sales category to the salesByCategory array, run a query using the $push operator on the field with a new Sales object with the name of the category and its sales volume. + +```javascript +db.stores.update({ + _id: "0fcc0bf0-ed18-4ab8-b558-9848e18058f4" +}, { + $push: { + "sales.salesByCategory": { + categoryName: "Wine Accessories", + totalSales: 1000.00 + } + } +}) +``` + +This query returns the following result: + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] +``` + +### Example 2 - Using $push with $setWindowFields + +To retrieve the distinct sales volumes across all stores under the "First Up Consultants" company, first run a query to partition stores within the company. Then, use the $push operator to create a list of sales from the first to the current store within the partition. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["First Up Consultants"] + } + } +}, { + $setWindowFields: { + partitionBy: "$company", + sortBy: { + "sales.totalSales": -1 + }, + output: { + salesByStore: { + $push: "$sales.totalSales", + window: { + documents: ["unbounded", "current"] + } + } + } + } +}, { + $project: { + company: 1, + salesByStore: 1 + } +}]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "a0386810-b6f8-4b05-9d60-e536fb2b0026", + "company": "First Up Consultants", + "salesByStore": [ + 327583 + ] + }, + { + "_id": "ad8af64a-d5bb-4162-9bb6-e5104126566d", + "company": "First Up Consultants", + "salesByStore": [ + 327583, + 288582 + ] + }, + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "company": "First Up Consultants", + "salesByStore": [ + 327583, + 288582, + 279183 + ] + } +] +``` diff --git a/api-reference/operators/bitwise-query/$bitsAllClear.md b/api-reference/operators/bitwise-query/$bitsAllClear.md new file mode 100644 index 0000000..e19918f --- /dev/null +++ b/api-reference/operators/bitwise-query/$bitsAllClear.md @@ -0,0 +1,215 @@ +--- +title: $bitsAllClear +description: The $bitsAllClear operator is used to match documents where all the bit positions specified in a bitmask are clear. +type: operators +category: bitwise-query +--- + +# $bitsAllClear + +The `$bitsAllClear` operator is used to match documents where all the bit positions specified in a bitmask are clear (that is, 0). This operator is useful in scenarios where you need to filter documents based on specific bits being unset in a binary representation of a field. + +## Syntax + +```javascript +{ + : { $bitsAllClear: } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field in the document on which the bitwise operation is to be performed.| +| **``** | A bitmask where each bit position specifies the corresponding bit position in the field's value that must be clear (0).| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +The `storeFeatures` field is a bitmask integer representing various store capabilities. Each bit corresponds to a feature: + +| Bit | Value | Feature | +|-----|-------|--------------------------| +| 0 | 1 | In-Store Pickup | +| 1 | 2 | Parking | +| 2 | 4 | Wheelchair Access | +| 3 | 8 | Open 24 Hours | +| 4 | 16 | Pet-Friendly | +| 5 | 32 | Free Wi-Fi | +| 6 | 64 | Restrooms | +| 7 | 128 | Home Delivery | + +### Example 1: Find stores that are not open 24 hours and do not allow pets + +This query retrieves stores that are NOT open 24 hours AND do NOT allow pets (bits 3 and 4) + +```javascript +db.stores.find({ + storeFeatures: { + $bitsAllClear: [3, 4] + } +}, { + _id: 1, + name: 1, + storeFeatures: 1 +}).limit(5) +``` + +Equivalent: + +```javascript +db.stores.find({ + storeFeatures: { + $bitsAnySet: 24 + } + }, // 8 + 16 + { + _id: 1, + name: 1, + storeFeatures: 1 + }).limit(5) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "storeFeatures": 38 + }, + { + "_id": "94792a4c-4b03-466b-91f6-821c4a8b2aa4", + "name": "Fourth Coffee | Eyewear Shop - Lessiemouth", + "storeFeatures": 225 + }, + { + "_id": "1a2c387b-bb43-4b14-a6cd-cc05a5dbfbd5", + "name": "Contoso, Ltd. | Smart Home Device Vault - Port Katarina", + "storeFeatures": 36 + }, + { + "_id": "e88f0096-4299-4944-9788-695c40786d97", + "name": "Adatum Corporation | Handbag Shoppe - Lucienneberg", + "storeFeatures": 135 + }, + { + "_id": "bfb213fa-8db8-419f-8e5b-e7096120bad2", + "name": "First Up Consultants | Beauty Product Shop - Hansenton", + "storeFeatures": 135 + } +] +``` diff --git a/api-reference/operators/bitwise-query/$bitsAllSet.md b/api-reference/operators/bitwise-query/$bitsAllSet.md new file mode 100644 index 0000000..58687cc --- /dev/null +++ b/api-reference/operators/bitwise-query/$bitsAllSet.md @@ -0,0 +1,214 @@ +--- +title: $bitsAllSet +description: The bitsAllSet command is used to match documents where all the specified bit positions are set. +type: operators +category: bitwise-query +--- + +# $bitsAllSet + +The `$bitsAllSet` operator is used to match documents where all the specified bit positions are set (that is, are 1). This operator is useful for performing bitwise operations on fields that store integer values. It can be used in scenarios where you need to filter documents based on specific bits being set within an integer field. + +## Syntax + +```javascript +{ + : { $bitsAllSet: } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field in the document on which the bitwise operation is to be performed.| +| **``** | A bitmask indicating which bits must be set in the field's value.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +The `storeFeatures` field is a bitmask integer representing various store capabilities. Each bit corresponds to a feature: + +| Bit | Value | Feature | +|-----|-------|--------------------------| +| 0 | 1 | In-Store Pickup | +| 1 | 2 | Parking | +| 2 | 4 | Wheelchair Access | +| 3 | 8 | Open 24 Hours | +| 4 | 16 | Pet-Friendly | +| 5 | 32 | Free Wi-Fi | +| 6 | 64 | Restrooms | +| 7 | 128 | Home Delivery | + +### Example 1: Find stores that have parking and restrooms + +This query retrieves stores that **have parking AND restrooms** (bits 1 and 6) + +```javascript +db.stores.find({ + storeFeatures: { + $bitsAllSet: [1, 6] + } +}, { + _id: 1, + name: 1, + storeFeatures: 1 +}).limit(5) +``` + +Equivalent: + +```javascript +db.stores.find({ + storeFeatures: { + $bitsAllSet: 66 + } +}, { + _id: 1, + name: 1, + storeFeatures: 1 +}).limit(5) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "name": "Contoso, Ltd. | Office Supply Deals - South Shana", + "storeFeatures": 86 + }, + { + "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", + "name": "Fourth Coffee | Storage Solution Gallery - Port Camilla", + "storeFeatures": 222 + }, + { + "_id": "728c068a-638c-40af-9172-8ccfa7dddb49", + "name": "Contoso, Ltd. | Book Store - Lake Myron", + "storeFeatures": 239 + }, + { + "_id": "a2b54e5c-36cd-4a73-b547-84e21d91164e", + "name": "Contoso, Ltd. | Baby Products Corner - Port Jerrold", + "storeFeatures": 126 + }, + { + "_id": "dda2a7d2-6984-40cc-bbea-4cbfbc06d8a3", + "name": "Contoso, Ltd. | Home Improvement Closet - Jaskolskiview", + "storeFeatures": 107 + } +] +``` diff --git a/api-reference/operators/bitwise-query/$bitsAnyClear.md b/api-reference/operators/bitwise-query/$bitsAnyClear.md new file mode 100644 index 0000000..2bbea5d --- /dev/null +++ b/api-reference/operators/bitwise-query/$bitsAnyClear.md @@ -0,0 +1,215 @@ +--- +title: $bitsAnyClear +description: The $bitsAnyClear operator matches documents where any of the specified bit positions in a bitmask are clear. +type: operators +category: bitwise-query +--- + +# $bitsAnyClear + +This operator is used to match documents where any of the bit positions specified in a bitmask are clear (that is, 0). It's useful for querying documents with binary data or flags stored as integers. This operator enables efficient querying based on specific bit patterns. + +## Syntax + +```javascript +{ + : { $bitsAnyClear: } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field in the document to be queried.| +| **``** |A bitmask where each bit position represents a position to check if it's clear (0).| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +The `storeFeatures` field is a bitmask integer representing various store capabilities. Each bit corresponds to a feature: + +| Bit | Value | Feature | +|-----|-------|--------------------------| +| 0 | 1 | In-Store Pickup | +| 1 | 2 | Parking | +| 2 | 4 | Wheelchair Access | +| 3 | 8 | Open 24 Hours | +| 4 | 16 | Pet-Friendly | +| 5 | 32 | Free Wi-Fi | +| 6 | 64 | Restrooms | +| 7 | 128 | Home Delivery | + +### Example 1: Find stores that don’t have Wi-Fi or in-store pickup + +This query retrieves stores that don’t have either Wi-Fi OR in-store pickup (bits 0 and 5) + +```javascript +db.stores.find({ + storeFeatures: { + $bitsAnyClear: [0, 5] + } +}, { + _id: 1, + name: 1, + storeFeatures: 1 +}).limit(5) +``` + +Equivalent: + +```javascript +db.stores.find({ + storeFeatures: { + $bitsAnySet: 33 + } + }, // 1 + 32 + { + _id: 1, + name: 1, + storeFeatures: 1 + }).limit(5) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "storeFeatures": 38 + }, + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "name": "Contoso, Ltd. | Office Supply Deals - South Shana", + "storeFeatures": 86 + }, + { + "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", + "name": "Fourth Coffee | Storage Solution Gallery - Port Camilla", + "storeFeatures": 222 + }, + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "name": "Relecloud | Toy Collection - North Jaylan", + "storeFeatures": 108 + }, + { + "_id": "9024d615-eed0-429a-a098-6640207cc2b6", + "name": "Adatum Corporation | Paper Product Mart - Lake Coralie", + "storeFeatures": 204 + } +] +``` diff --git a/api-reference/operators/bitwise-query/$bitsAnySet.md b/api-reference/operators/bitwise-query/$bitsAnySet.md new file mode 100644 index 0000000..4b41df1 --- /dev/null +++ b/api-reference/operators/bitwise-query/$bitsAnySet.md @@ -0,0 +1,215 @@ +--- +title: $bitsAnySet +description: The $bitsAnySet operator returns documents where any of the specified bit positions are set to 1. +type: operators +category: bitwise-query +--- + +# $bitsAnySet + +This operator is used to select documents where any of the bit positions specified are set to `1`. It's useful for querying documents with fields that store bitmask values. This operator can be handy when working with fields that represent multiple boolean flags in a single integer. + +## Syntax + +```javascript +{ + : { $bitsAnySet: [ ] } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to be queried.| +| **``** | An array of bit positions to check if any are set to `1`.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +The `storeFeatures` field is a bitmask integer representing various store capabilities. Each bit corresponds to a feature: + +| Bit | Value | Feature | +|-----|-------|--------------------------| +| 0 | 1 | In-Store Pickup | +| 1 | 2 | Parking | +| 2 | 4 | Wheelchair Access | +| 3 | 8 | Open 24 Hours | +| 4 | 16 | Pet-Friendly | +| 5 | 32 | Free Wi-Fi | +| 6 | 64 | Restrooms | +| 7 | 128 | Home Delivery | + +### Example 1: Find stores that have in-store pickup or drive-thru + +This query retrieves stores that offer either home delivery OR free Wi-Fi (bits 5 and 7) + +```javascript +db.stores.find({ + storeFeatures: { + $bitsAnySet: [5, 7] + } +}, { + _id: 1, + name: 1, + storeFeatures: 1 +}).limit(5) +``` + +Equivalent: + +```javascript +db.stores.find({ + storeFeatures: { + $bitsAnySet: 160 + } + }, // 32 + 128 + { + _id: 1, + name: 1, + storeFeatures: 1 + }).limit(5) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "storeFeatures": 38 + }, + { + "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", + "name": "Fourth Coffee | Storage Solution Gallery - Port Camilla", + "storeFeatures": 222 + }, + { + "_id": "94792a4c-4b03-466b-91f6-821c4a8b2aa4", + "name": "Fourth Coffee | Eyewear Shop - Lessiemouth", + "storeFeatures": 225 + }, + { + "_id": "728c068a-638c-40af-9172-8ccfa7dddb49", + "name": "Contoso, Ltd. | Book Store - Lake Myron", + "storeFeatures": 239 + }, + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "name": "Relecloud | Toy Collection - North Jaylan", + "storeFeatures": 108 + } +] +``` diff --git a/api-reference/operators/bitwise-update/$bit.md b/api-reference/operators/bitwise-update/$bit.md new file mode 100644 index 0000000..1e68b9b --- /dev/null +++ b/api-reference/operators/bitwise-update/$bit.md @@ -0,0 +1,228 @@ +--- +title: $bit +description: The `$bit` operator is used to perform bitwise operations on integer values. +type: operators +category: bitwise-update +--- + +# $bit + +The `$bit` operator is used to perform bitwise operations on integer values. It can be used to update integer fields in documents by applying bitwise AND, OR, and XOR operations. Bitwise operators like $bit aren't designed for incrementing values, but for manipulating bits directly (like checking, setting, or clearing specific bits). + +## Syntax + +```javascript +{ + $bit: { + < field >: { + < operator >: < number > + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The field to perform the bitwise operation on. | +| **``** | The bitwise operation to perform. Can be one of: `and`, `or`, `xor`. | +| **``** | The number to use for the bitwise operation. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Perform a bitwise AND operation on the `partTime` field in `totalStaff` + +```javascript +db.stores.updateOne({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" +}, { + $bit: { + "staff.totalStaff.partTime": { + and: 1 + } + } +}) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] +``` + +### Example 2: Perform a bitwise OR operation on the `partTime` field in `totalStaff` + +```javascript +db.stores.updateOne({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" +}, { + $bit: { + "staff.totalStaff.partTime": { + "or": 1 + } + } +}) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] +``` + +### Example 3: Perform a bitwise XOR operation on the `partTime` field in `totalStaff` + +```javascript +db.stores.updateOne({ + _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" +}, { + $bit: { + "staff.totalStaff.partTime": { + "xor": 1 + } + } +}) +``` + +This query returns the following result. + +```json +[ + { + "acknowledged": true, + "insertedId": null, + "matchedCount": "1", + "modifiedCount": "1", + "upsertedCount": 0 + } +] +``` diff --git a/api-reference/operators/bitwise/$bitand.md b/api-reference/operators/bitwise/$bitand.md new file mode 100644 index 0000000..0941001 --- /dev/null +++ b/api-reference/operators/bitwise/$bitand.md @@ -0,0 +1,212 @@ +--- +title: $bitAnd +description: The $bitAnd operator performs a bitwise AND operation on integer values and returns the result as an integer. +type: operators +category: bitwise +--- + +# $bitAnd + +The `$bitAnd` operator performs a `bitwise AND` operation on integer values. It compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. + +## Syntax + +```javascript +{ + $bitAnd: [ , , ... ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression1, expression2, ...`** | Expressions that evaluate to integers. The `$bitAnd` operator performs a bitwise AND operation on all provided expressions. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic bitwise AND operation + +This query retrieves staff information for a specific store and computes a `bitwise AND` between the number of full-time and part-time staff to create permission flags. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + fullTimeStaff: "$staff.totalStaff.fullTime", + partTimeStaff: "$staff.totalStaff.partTime", + staffPermissionFlag: { + $bitAnd: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "fullTimeStaff": 19, + "partTimeStaff": 20, + "staffPermissionFlag": 16 + } +] +``` + +### Example 2: Multiple value `$bitAnd` + +This query checks bitwise permissions or combined flags based on multiple numeric fields for a single store. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + combinedFlag: { + $bitAnd: [ + "$staff.totalStaff.fullTime", + "$staff.totalStaff.partTime", + 255 + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "combinedFlag": 16 + } +] +``` diff --git a/api-reference/operators/bitwise/$bitnot.md b/api-reference/operators/bitwise/$bitnot.md new file mode 100644 index 0000000..b92d8ef --- /dev/null +++ b/api-reference/operators/bitwise/$bitnot.md @@ -0,0 +1,237 @@ +--- +title: $bitNot +description: The $bitNot operator performs a bitwise NOT operation on integer values and returns the result as an integer. +type: operators +category: bitwise +--- + +# $bitNot + +The `$bitNot` operator performs a bitwise NOT operation on integer values. It inverts all the bits of the operand, turning 1s into 0s and 0s into 1s. The result is the bitwise complement of the input value. + +## Syntax + +```javascript +{ + $bitNot: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | An expression that evaluates to an integer. The `$bitNot` operator performs a bitwise NOT operation on this value. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic bitwise NOT operation + +This query performs a bitwise inversion on the staff count fields for a specific store document. The inverted values can be used for special permission flags, feature toggles, or bitmask operations. The bitwise NOT of 14 results are -15, and the bitwise NOT of 8 results in -9. The observed result is due to two's complement representation where ~n = -(n+1). + +```javascript +db.stores.aggregate([{ + $match: { + _id: "26afb024-53c7-4e94-988c-5eede72277d5" + } + }, + { + $project: { + name: 1, + fullTimeStaff: "$staff.totalStaff.fullTime", + partTimeStaff: "$staff.totalStaff.partTime", + invertedFullTime: { + $bitNot: "$staff.totalStaff.fullTime" + }, + invertedPartTime: { + $bitNot: "$staff.totalStaff.partTime" + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "fullTimeStaff": 14, + "partTimeStaff": 8, + "invertedFullTime": -15, + "invertedPartTime": -9 + } +] +``` + +### Example 2: Using $bitNot with discount percentages + +This query extracts and processes discount information for a specific store and applies a bitwise NOT operation on each discount percentage. The bitwise NOT operation inverts all bits: 20 becomes -21 and 17 becomes -18. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "26afb024-53c7-4e94-988c-5eede72277d5" + } + }, + { + $unwind: "$promotionEvents" + }, + { + $match: { + "promotionEvents.eventName": "Incredible Savings Showcase" + } + }, + { + $unwind: "$promotionEvents.discounts" + }, + { + $project: { + name: 1, + eventName: "$promotionEvents.eventName", + categoryName: "$promotionEvents.discounts.categoryName", + discountPercentage: "$promotionEvents.discounts.discountPercentage", + invertedDiscount: { + $bitNot: "$promotionEvents.discounts.discountPercentage" + } + } + } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "eventName": "Incredible Savings Showcase", + "categoryName": "Microphone Stands", + "discountPercentage": 17, + "invertedDiscount": -18 + }, + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "eventName": "Incredible Savings Showcase", + "categoryName": "Condenser Microphones", + "discountPercentage": 20, + "invertedDiscount": -21 + } +] +``` diff --git a/api-reference/operators/bitwise/$bitor.md b/api-reference/operators/bitwise/$bitor.md new file mode 100644 index 0000000..4a59a14 --- /dev/null +++ b/api-reference/operators/bitwise/$bitor.md @@ -0,0 +1,243 @@ +--- +title: $bitOr +description: The $bitOr operator performs a bitwise OR operation on integer values and returns the result as an integer. +type: operators +category: bitwise +--- + +# $bitOr + +The `$bitOr` operator performs a bitwise OR operation on integer values. It compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. If both bits are 0, the corresponding result bit is set to 0. + +## Syntax + +```javascript +{ + $bitOr: [ , , ... ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression1, expression2, ...`** | Expressions that evaluate to integers. The `$bitOr` operator performs a bitwise OR operation on all provided expressions. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic bitwise OR operation + +This query performs a bitwise OR operation on the staff values of a specific store document to combine permission flags. The bitwise OR of 3 (011 in binary) and 2 (010 in binary) equals 3 (011 in binary). + +```javascript +db.stores.aggregate([{ + $match: { + _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" + } + }, + { + $project: { + name: 1, + fullTimeStaff: "$staff.totalStaff.fullTime", + partTimeStaff: "$staff.totalStaff.partTime", + combinedStaffFlag: { + $bitOr: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "f2a8c190-28e4-4e14-9d8b-0256e53dca66", + "name": "Fabrikam, Inc. | Car Accessory Outlet - West Adele", + "fullTimeStaff": 3, + "partTimeStaff": 2, + "combinedStaffFlag": 3 + } +] +``` + +### Example 2: Multiple value bitwise OR with discount percentages + +This query extracts discount details for a specific promotion event and computes a bitwise flag combining discounts and staff values. The output shows the results of the aggregation query that calculates a combined bitwise flag for each discount in the event `Super Saver Spectacular`. The operation combines discount percentages with staff numbers using bitwise OR: 7|3|2 = 7 and 11|3|2 = 11. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" + } + }, + { + $unwind: "$promotionEvents" + }, + { + $match: { + "promotionEvents.eventName": "Super Saver Spectacular" + } + }, + { + $project: { + name: 1, + eventName: "$promotionEvents.eventName", + discountFlags: { + $map: { + input: "$promotionEvents.discounts", + as: "discount", + in: { + categoryName: "$$discount.categoryName", + discountPercentage: "$$discount.discountPercentage", + combinedFlag: { + $bitOr: [ + "$$discount.discountPercentage", + "$staff.totalStaff.fullTime", + "$staff.totalStaff.partTime" + ] + } + } + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "f2a8c190-28e4-4e14-9d8b-0256e53dca66", + "name": "Fabrikam, Inc. | Car Accessory Outlet - West Adele", + "eventName": "Super Saver Spectacular", + "discountFlags": [ + { + "categoryName": "Car Chargers", + "discountPercentage": 7, + "combinedFlag": 7 + }, + { + "categoryName": "Dash Cameras", + "discountPercentage": 11, + "combinedFlag": 11 + } + ] + } +] +``` diff --git a/api-reference/operators/bitwise/$bitxor.md b/api-reference/operators/bitwise/$bitxor.md new file mode 100644 index 0000000..e197c98 --- /dev/null +++ b/api-reference/operators/bitwise/$bitxor.md @@ -0,0 +1,253 @@ +--- +title: $bitXor +description: The $bitXor operator performs a bitwise XOR operation on integer values. +type: operators +category: bitwise +--- + +# $bitXor + +The `$bitXor` operator performs a bitwise exclusive OR (XOR) operation on integer values. The XOR operation returns 1 for each bit position where the corresponding bits of the operands are different, and 0 where they're the same. + +## Syntax + +```javascript +{ + $bitXor: [ , , ... ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression1, expression2, ...`** | Expressions that resolve to integer values. The operator performs XOR operations on these values in sequence. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic XOR operation + +This query uses an aggregation pipeline to calculate between full-time and part-time staff counts for a specific store. The resulting document contains the store details along with a computed field. The XOR operation between 19 (binary: 10011) and 20 (binary: 10100) results in 7 (binary: 00111). + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $project: { + name: 1, + fullTimeStaff: "$staff.totalStaff.fullTime", + partTimeStaff: "$staff.totalStaff.partTime", + staffXor: { + $bitXor: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "fullTimeStaff": 19, + "partTimeStaff": 20, + "staffXor": 7 + } +] +``` + +### Example 2: XOR with Multiple Values + +This query computes the bitwise XOR of all discount percentages for the `Discount Delight Days` event of a specific store. The resulting document represents the bitwise XOR calculation of all discount percentages for the `Discount Delight Days` event. + +```javascript +db.stores.aggregate([{ + $match: { + _id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" + } + }, + { + $unwind: "$promotionEvents" + }, + { + $match: { + "promotionEvents.eventName": "Discount Delight Days" + } + }, + { + $unwind: "$promotionEvents.discounts" + }, + { + $group: { + _id: "$_id", + name: { + $first: "$name" + }, + eventName: { + $first: "$promotionEvents.eventName" + }, + discountPercentages: { + $push: "$promotionEvents.discounts.discountPercentage" + } + } + }, + { + $project: { + name: 1, + eventName: 1, + discountPercentages: 1, + xorResult: { + $reduce: { + input: { + $map: { + input: "$discountPercentages", + as: "val", + in: { + $toLong: "$$val" + } + } + }, + initialValue: { + $toLong: 0 + }, + in: { + $bitXor: ["$$value", "$$this"] + } + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "eventName": "Discount Delight Days", + "discountPercentages": [22, 23, 10, 10, 9, 24], + "xorResult": { "$numberLong": "16" } + } +] +``` diff --git a/api-reference/operators/comparison-query/$cmp.md b/api-reference/operators/comparison-query/$cmp.md new file mode 100644 index 0000000..fac650d --- /dev/null +++ b/api-reference/operators/comparison-query/$cmp.md @@ -0,0 +1,195 @@ +--- +title: $cmp +description: The $cmp operator compares two values +type: operators +category: comparison-query +--- + +# $cmp + +The `$cmp` operator compares two specified values. The $cmp operator returns -1 if the first value is less than the second, 0 if the two values are equal and 1 if the first value is greater than the second. + +## Syntax + +```javascript +{ + $cmp: [, ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The first value which is compared to the second by the $cmp operator| +| **``** | The second value being compared to by the $cmp operator| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Compare the total sales of stores to $25,000 + +To compare the total sales of stores within the Boulder Innovations Company to $25,000, first run a query to filter on the company name of stores. Then, use $cmp to compare the sales.totalSales field to 25000. Lastly, project only the name and total sales for the resulting stores. + +```javascript +db.stores.aggregate([{ + $match: { + company: { + $in: ["Boulder Innovations"] + } + } +}, { + $project: { + name: 1, + "sales.salesByCategory.totalSales": 1, + greaterThan25000: { + $cmp: ["$sales.revenue", 25000] + } + } +}]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "a5040801-d127-4950-a320-e55f6aed4b36", + "name": "Boulder Innovations | DJ Equipment Pantry - West Christopher", + "sales": { + "salesByCategory": [ + { + "totalSales": 21522 + } + ] + }, + "greaterThan25000": -1 + }, + { + "_id": "bb6e097a-e204-4b64-9f13-5ae8426fcc76", + "name": "Boulder Innovations | Kitchen Appliance Outlet - Lake Chazville", + "sales": { + "salesByCategory": [ + { + "totalSales": 24062 + }, + { + "totalSales": 24815 + } + ] + }, + "greaterThan25000": 1 + } +] +``` diff --git a/api-reference/operators/comparison-query/$eq.md b/api-reference/operators/comparison-query/$eq.md new file mode 100644 index 0000000..c4ae35c --- /dev/null +++ b/api-reference/operators/comparison-query/$eq.md @@ -0,0 +1,263 @@ +--- +title: $eq +description: The $eq query operator compares the value of a field to a specified value +type: operators +category: comparison-query +--- + +# $eq + +The `$eq` operator is used to match documents where the value of a field is equal to a specified value. The $eq operator filters documents based on exact matches on query predicates to retrieve documents with specific values, objects and arrays. + +## Syntax + +```javascript +{ + field: { + $eq: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to be compared| +| **`value`** | The value to compare against| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Use $eq filter on a root level field + +To find a store with the name "Boulder Innovations | Home Security Place - Ankundingburgh", run a query with the $eq predicate to match on the name field and project only the ID and name fields in the result. + +```javascript +db.stores.find({ + name: { + $eq: "Boulder Innovations | Home Security Place - Ankundingburgh" + } +}, { + name: 1 +}) +``` + +This query returns the following result: + +```json +[ + { + "_id": "bda56164-954d-4f47-a230-ecf64b317b43", + "name": "Boulder Innovations | Home Security Place - Ankundingburgh" + } +] +``` + +### Example 2: Use $eq filter on a nested field + +To find a store with a total sales of exactly $37,015, run a query using the $eq operator using the dot notation on the nested field sales.totalSales field. + +```javascript +db.stores.find({ + "sales.totalSales": { + $eq: 37015 + } +}, { + name: 1, + "sales.totalSales": 1 +}) +``` + +This returns the following result: + +```json +[ + { + "_id": "bda56164-954d-4f47-a230-ecf64b317b43", + "name": "Boulder Innovations | Home Security Place - Ankundingburgh", + "sales": { "totalSales": 37015 } + } +] +``` + +### Example 3: Use $eq for individual items in an array + +The following query retrieves documents using equality predicates on individual items within the nested promotionEvents.discounts array. + +This query searches for an equality match on any one of the objects within the nested discounts array + +```javascript +db.stores.find({ + "promotionEvents.discounts": { + $eq: { + categoryName: "Alarm Systems", + discountPercentage: 5 + } + } +}, { + name: 1 +}, { + limit: 2 +}) +``` + +This query returns the following results: + +```json +[ + { + "_id": "ece5bf6c-3255-477e-bf2c-d577c82d6995", + "name": "Proseware, Inc. | Home Security Boutique - Schambergertown" + }, + { + "_id": "7baa8fd8-113a-4b10-a7b9-2c116e976491", + "name": "Tailwind Traders | Home Security Pantry - Port Casper" + } +] +``` + +### Example 4: Use $eq to match the entire array + +This query searches for documents based on exact match on ALL the values within the promotionEvents.discounts array. + +```javascript +db.stores.find({ + "promotionEvents.discounts": { + $eq: [{ + categoryName: "Alarm Systems", + discountPercentage: 5 + }, { + categoryName: "Door Locks", + discountPercentage: 12 + }] + } +}, { + name: 1 +}) +``` + +This query returns the following result: + +```json +[ + { + "_id": "aa9ad64c-29da-42f8-a1f0-30e03bf04a2d", + "name": "Boulder Innovations | Home Security Market - East Sheridanborough" + } +] +``` + +> [!NOTE] +> For an equality match on an entire array, the order of the specified values in the equality predicates must also be an exact match. diff --git a/api-reference/operators/comparison-query/$gt.md b/api-reference/operators/comparison-query/$gt.md new file mode 100644 index 0000000..60d6d82 --- /dev/null +++ b/api-reference/operators/comparison-query/$gt.md @@ -0,0 +1,199 @@ +--- +title: $gt +description: The $gt query operator retrieves documents where the value of a field is greater than a specified value +type: operators +category: comparison-query +--- + +# $gt + +The `$gt` operator retrieves documents where the value of a field is greater than a specified value. The `$gt` operator queries numerical and date values to filter records that exceed a specified threshold. + +## Syntax + +```javascript +{ + field: { + $gt: value + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field in the document you want to compare| +| **`value`** | The value that the field should be greater than| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Retrieve stores with sales exceeding $35,000 + +To retrieve a store with over $35,000 in sales, first run a query with $gt operator on the sales.totalSales field. Then limit the query results to one store. + +```javascript +db.stores.find({ + "sales.totalSales": { + $gt: 35000 + } +}, { + name: 1, + "sales.totalSales": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "sales": { "totalSales": 37701 } + } +] +``` + +### Example 2: Find a store with more than 12 full-time staff + +To find a store with more than 12 full time staff, first run a query with the $gt operator on the staff.totalStaff.fullTime field. Then project just the name and totalStaff fields and limit the result set to a single store from the list of matching results. + +```javascript +db.stores.find({ + "staff.totalStaff.fullTime": { + $gt: 12 + } +}, { + name: 1, + "staff.totalStaff": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "staff": { "totalStaff": { "fullTime": 18, "partTime": 17 } } + } +] +``` diff --git a/api-reference/operators/comparison-query/$gte.md b/api-reference/operators/comparison-query/$gte.md new file mode 100644 index 0000000..9bfa22e --- /dev/null +++ b/api-reference/operators/comparison-query/$gte.md @@ -0,0 +1,235 @@ +--- +title: $gte +description: The $gte operator retrieves documents where the value of a field is greater than or equal to a specified value +type: operators +category: comparison-query +--- + +# $gte + +The `$gte` operator retrieves documents where the value of a field is greater than or equal to a specified value. The `$gte` operator retrieves documents that meet a minimum threshold for the value of a field. + +## Syntax + +```javascript +{ + field: { + $gte: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field in the document you want to compare| +| **`value`** | The value that the field should be greater than| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find a store with sales >= $35,000 + +To retrieve a store with at least $35,000 in sales, first run a query using the $gte operator on the sales.totalSales field. Then project only the name of the store and its total sales and limit the result set to one document. + +```javascript +db.stores.find({ + "sales.totalSales": { + $gte: 35000 + } +}, { + name: 1, + "sales.totalSales": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "sales": { "totalSales": 37701 } + } +] +``` + +### Example 2: Find a store with 12 or more full-time staff + +To retrieve a store with at least 12 full time staff, first run a query with the $gte operator on the staff.totalStaff.fullTime field. Then, project only the name and full time staff count and limit the results to a single document from the result set. + +```javascript +db.stores.find({ + "staff.totalStaff.fullTime": { + $gte: 12 + } +}, { + name: 1, + "staff.totalStaff.fullTime": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "staff": { "totalStaff": { "fullTime": 18 } } + } +] +``` + +### Example 3: Find promotion events with a discount percentage greater than or equal to 15% for Laptops + +To find two stores with promotions with a discount of at least 15% for laptops, first run a query to filter stores with laptop promotions. Then use the $gte operator on the discountPercentage field. Lastly, project only the name of the store and limit the results to two documents from the result set. + +```javascript +db.stores.find({ + "promotionEvents.discounts": { + $elemMatch: { + categoryName: "Laptops", + discountPercentage: { + $gte: 15 + } + } + } +}, { + name: 1 +}, { + limit: 2 +}) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "60e43617-8d99-4817-b1d6-614b4a55c71e", + "name": "Wide World Importers | Electronics Emporium - North Ayanashire" + }, + { + "_id": "3c441d5a-c9ad-47f4-9abc-ac269ded44ff", + "name": "Contoso, Ltd. | Electronics Corner - New Kiera" + } +] +``` diff --git a/api-reference/operators/comparison-query/$in.md b/api-reference/operators/comparison-query/$in.md new file mode 100644 index 0000000..06fbf5b --- /dev/null +++ b/api-reference/operators/comparison-query/$in.md @@ -0,0 +1,252 @@ +--- +title: $in +description: The $in operator matches value of a field against an array of specified values +type: operators +category: comparison-query +--- + +# $in + +The `$in` operator matches values of a field against an array of possible values. The `$in` operator filters documents where the value of a field equals any of the specified values. + +## Syntax + +```javascript +{ + field: { + $in: [ listOfValues ] + } +} +``` + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Use $in operator as comparison-query to find a store with specific categories of promotions + +This query finds stores that offer discounts in either "Smoked Salmon" or "Anklets" categories via promotion events. + +```javascript +db.stores.find({ + "promotionEvents.discounts.categoryName": { + $in: ["Smoked Salmon", "Anklets"] + } +}, { + name: 1, + "promotionEvents.discounts.categoryName": 1 +}).limit(1) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "48fcdab8-b961-480e-87a9-19ad880e9a0a", + "name": "Lakeshore Retail | Jewelry Collection - South Nicholas", + "promotionEvents": [ + { + "discounts": [ + {"categoryName": "Anklets"}, + {"categoryName": "Cufflinks"} + ] + }, + { + "discounts": [ + {"categoryName": "Anklets"}, + {"categoryName": "Brooches"} + ] + }, + { + "discounts": [ + {"categoryName": "Rings"}, + {"categoryName": "Bracelets"} + ] + }, + { + "discounts": [ + {"categoryName": "Charms"}, + {"categoryName": "Bracelets"} + ] + }, + { + "discounts": [ + {"categoryName": "Watches"}, + {"categoryName": "Pendants"} + ] + } + ] + } +] +``` + +### Example 2 - Use $in operator as array-expression in an array for a specified value or set of values + +This query searches for the specified store and filters documents where at least one `discountPercentage` within any `promotionEvents.discounts` is either 15 or 20. It uses a dot notation path and the $in operator to match nested discount values across the array hierarchy. + +```javascript +db.stores.find({ + _id: "48fcdab8-b961-480e-87a9-19ad880e9a0a", + "promotionEvents.discounts.discountPercentage": { + $in: [15, 20] + } +}, { + _id: 1, + name: 1, + "promotionEvents.discounts": 1 +}) +``` + +This query returns the following result: + +```json +[ + { + "_id": "48fcdab8-b961-480e-87a9-19ad880e9a0a", + "name": "Lakeshore Retail | Jewelry Collection - South Nicholas", + "promotionEvents": [ + { + "discounts": [ + { "categoryName": "Anklets", "discountPercentage": 12 }, + { "categoryName": "Cufflinks", "discountPercentage": 9 } + ] + }, + { + "discounts": [ + { "categoryName": "Anklets", "discountPercentage": 23 }, + { "categoryName": "Brooches", "discountPercentage": 12 } + ] + }, + { + "discounts": [ + { "categoryName": "Rings", "discountPercentage": 10 }, + { "categoryName": "Bracelets", "discountPercentage": 21 } + ] + }, + { + "discounts": [ + { "categoryName": "Charms", "discountPercentage": 9 }, + { "categoryName": "Bracelets", "discountPercentage": 13 } + ] + }, + { + "discounts": [ + { "categoryName": "Watches", "discountPercentage": 20 }, + { "categoryName": "Pendants", "discountPercentage": 7 } + ] + } + ] + } +] +``` diff --git a/api-reference/operators/comparison-query/$lt.md b/api-reference/operators/comparison-query/$lt.md new file mode 100644 index 0000000..514fa4f --- /dev/null +++ b/api-reference/operators/comparison-query/$lt.md @@ -0,0 +1,170 @@ +--- +title: $lt +description: The $lt operator retrieves documents where the value of field is less than a specified value +type: operators +category: comparison-query +--- + +# $lt + +The `$lt` operator retrieves documents where the value of a field is strictly less than a specified value. The `$lt` operator filters documents based on numeric, date, or string values. + +## Syntax + +```javascript +{ + field: { + $lt: value + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field in the document you want to evaluate| +| **`value`** | The value to compare against the field's value. The operator will match documents where the field's value is less than this specified value| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find a store with sales below $36,000 + +To find a store with less than $36,000 in sales, first run a query using $lt on the sales.totalSales field. Then project only the name and total sales of the resulting stores and limit the number of results to a single document. + +```javascript +db.stores.find({ + "sales.totalSales": { + $lt: 36000 + } +}, { + name: 1, + "sales.totalSales": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "e6895a31-a5cd-4103-8889-3b95a864e5a6", + "name": "VanArsdel, Ltd. | Picture Frame Store - Port Clevelandton", + "sales": { "totalSales": 17676 } + } +] +``` diff --git a/api-reference/operators/comparison-query/$lte.md b/api-reference/operators/comparison-query/$lte.md new file mode 100644 index 0000000..c10d03a --- /dev/null +++ b/api-reference/operators/comparison-query/$lte.md @@ -0,0 +1,196 @@ +--- +title: $lte +description: The $lte operator retrieves documents where the value of a field is less than or equal to a specified value +type: operators +category: comparison-query +--- + +# $lte + +The `$lte` operator retrieves documents where the value of a field is less than or equal to a specified value. The `$lte` operator filters documents based on numerical, date, or other comparable fields. + +## Syntax + +```javascript +{ + field: { + $lte: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to be compared| +| **`value`** | The value to compare against| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find a store with sales <= $35,000 + +To find a store with sales <= $35,000, run a query using $lte on the sales.totalSales field and limit the resulting documents to a single store. + +```javascript +db.stores.find({ + "sales.totalSales": { + $lte: 35000 + } +}, { + _id: 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "e6895a31-a5cd-4103-8889-3b95a864e5a6" + } +] +``` + +### Example 2: Find a store with 12 or fewer full-time staff + +To find a store with <= 12 full-time staff, run a query using $lte on the nested fullTime field. Then project only the name and full time staff count and limit the results to one store from the result set. + +```javascript +db.stores.find({ + "staff.totalStaff.fullTime": { + $lte: 12 + } +}, { + name: 1, + "staff.totalStaff.fullTime": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "e6895a31-a5cd-4103-8889-3b95a864e5a6", + "name": "VanArsdel, Ltd. | Picture Frame Store - Port Clevelandton", + "staff": { "totalStaff": { "fullTime": 6 } } + } +] +``` diff --git a/api-reference/operators/comparison-query/$ne.md b/api-reference/operators/comparison-query/$ne.md new file mode 100644 index 0000000..608e417 --- /dev/null +++ b/api-reference/operators/comparison-query/$ne.md @@ -0,0 +1,202 @@ +--- +title: $ne +description: The $ne operator retrieves documents where the value of a field doesn't equal a specified value +type: operators +category: comparison-query +--- + +# $ne + +The `$ne` operator retrieves documents where the value of a field doesn't equal a specified value. + +## Syntax + +```javascript +{ + field: { + $ne: value + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to be compared| +| **`value`** | The value that the field shouldn't be equal to| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Find a store whose name isn't "Fourth Coffee" + +To find a store with a name that isn't "Fourth Coffee", first run a query using $ne on the name field. Then project only the name of the resulting documents and limit the results to one store from the result set. + +```javascript +db.stores.find({ + name: { + $ne: "Fourth Coffee" + } +}, { + _id: 1, + name: 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir" + } +] +``` + +### Example 2 - Find a store with promotion events that aren't in 2024 + +To find a store with promotions events that don't start in 2024, first run a query using $ne on the nested startDate field. Then project the name and promotions offered by the stores and limit the results to one document from the result set. + +```javascript +db.stores.find({ + "promotionEvents.promotionalDates.startDate": { + $ne: "2024" + } +}, { + name: 1, + "promotionEvents.promotionalDates.startDate": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "promotionEvents": [ + { + "promotionalDates": { "startDate": { "Year": 2024, "Month": 9, "Day": 21 } } + } + ] + } +] +``` diff --git a/api-reference/operators/comparison-query/$nin.md b/api-reference/operators/comparison-query/$nin.md new file mode 100644 index 0000000..005735c --- /dev/null +++ b/api-reference/operators/comparison-query/$nin.md @@ -0,0 +1,229 @@ +--- +title: $nin +description: The $nin operator retrieves documents where the value of a field doesn't match a list of values +type: operators +category: comparison-query +--- + +# $nin + +The `$nin` operator retrieves documents where the value of a specified field doesn't match a list of values. + +## Syntax + +```javascript +{ + field: { + $nin: [ < listOfValues > ] + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to compare| +| **`[]`** | An array of values that shouldn't match the value of the field being compared| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Find a store with a discount that isn't 10%, 15%, or 20% + +To find a store with promotions offering discounts that are not 10%, 15%, or 20%, first run a query using $nin on the nested discountPercentage field. Then project only the name and discount offered by the result store and limit the result to a single document from the result set. + +```javascript +db.stores.find({ + "promotionEvents.discounts.discountPercentage": { + $nin: [10, 15, 20] + } +}, { + name: 1, + "promotionEvents.discounts.discountPercentage": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "promotionEvents": [ + { + "discounts": [ + { "discountPercentage": 18 }, + { "discountPercentage": 17 }, + { "discountPercentage": 9 }, + { "discountPercentage": 5 }, + { "discountPercentage": 5 }, + { "discountPercentage": 6 }, + { "discountPercentage": 9 }, + { "discountPercentage": 5 }, + { "discountPercentage": 19 }, + { "discountPercentage": 21 } + ] + } + ] + } +] +``` + +### Example 2 - Find a store with no discounts on specific categories of promotions + +To find a store without promotions on Smoked Salmon and Anklets, first run a query using $nin on the nested categoryName field. Then project the name and promotions offered by the store and limit the results to one document from the result set. + +```javascript +db.stores.find({ + "promotionEvents.discounts.categoryName": { + $nin: ["Smoked Salmon", "Anklets"] + } +}, { + name: 1, + "promotionEvents.discounts.categoryName": 1 +}, { + limit: 1 +}) +``` + +The first result returned by this query is: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "promotionEvents": [ + { + "discounts": [ + { "categoryName": "Bath Accessories" }, + { "categoryName": "Pillow Top Mattresses" }, + { "categoryName": "Bathroom Scales" }, + { "categoryName": "Towels" }, + { "categoryName": "Bathrobes" }, + { "categoryName": "Mattress Toppers" }, + { "categoryName": "Hand Towels" }, + { "categoryName": "Shower Heads" }, + { "categoryName": "Bedspreads" }, + { "categoryName": "Bath Mats" } + ] + } + ] + } +] +``` diff --git a/api-reference/operators/conditional-expression/$cond.md b/api-reference/operators/conditional-expression/$cond.md new file mode 100644 index 0000000..a9170c2 --- /dev/null +++ b/api-reference/operators/conditional-expression/$cond.md @@ -0,0 +1,269 @@ +--- +title: $cond +description: The $cond operator is used to evaluate a condition and return one of two expressions based on the result. +type: operators +category: conditional-expression +--- + +# $cond + +The `$cond` operator is used to evaluate a condition and return one of two expressions based on the result. It's similar to the ternary operator in many programming languages. The `$cond` operator can be used within aggregation pipelines to add conditional logic to your queries. + +## Syntax + +```javascript +{ + $cond: { + if: , + then: , + else: + } +} +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **if**| A boolean expression that is evaluated.| +| **then**| The expression to return if the `if` condition evaluates to true.| +| **else**| The expression to return if the `if` condition evaluates to false.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Determine high sales categories + +This query determines if the sales for each category are considered "high" or "low" based on a threshold value of $250,000. + +```javascript +db.stores.aggregate([{ + $project: { + _id: 0, + storeId: "$storeId", + category: "$sales.salesByCategory.categoryName", + sales: "$sales.salesByCategory.totalSales", + salesCategory: { + $cond: { + if: { + $gte: ["$sales.salesByCategory.totalSales", 250000] + }, + then: "High", + else: "Low" + } + } + } + }, + // Limit the result to the first 3 documents + { + $limit: 3 + } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "sales": [ + 35921, + 1000 + ], + "category": [ + "DJ Headphones", + "DJ Cables" + ], + "salesCategory": "High" + }, + { + "sales": [ + 4760 + ], + "category": [ + "Guitars" + ], + "salesCategory": "High" + }, + { + "sales": [ + 14697, + 44111, + 37854, + 46211, + 7269, + 25451, + 21083 + ], + "category": [ + "Washcloths", + "Innerspring Mattresses", + "Microfiber Towels", + "Shower Curtains", + "Bathrobes", + "Tablecloths", + "Bath Accessories" + ], + "salesCategory": "High" + } +] +``` + +### Example 2: Determine full-time or part-time dominance + +This query determines whether a store employs more full-time or part-time staff. + +```javascript +db.stores.aggregate([{ + $project: { + name: 1, + staffType: { + $cond: { + if: { + $gte: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] + }, + then: "More Full-Time", + else: "More Part-Time" + } + } + } + }, + // Limit the result to the first 3 documents + { + $limit: 3 + } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "staffType": "More Full-Time" + }, + { + "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41", + "name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie", + "staffType": "More Full-Time" + }, + { + "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34", + "name": "Northwind Traders | Bed and Bath Place - West Oraland", + "staffType": "More Part-Time" + } +] +``` diff --git a/api-reference/operators/conditional-expression/$ifnull.md b/api-reference/operators/conditional-expression/$ifnull.md new file mode 100644 index 0000000..c6cfcbe --- /dev/null +++ b/api-reference/operators/conditional-expression/$ifnull.md @@ -0,0 +1,179 @@ +--- +title: $ifNull +description: The $ifNull operator is used to evaluate an expression and return a specified value if the expression resolves to null. +type: operators +category: conditional-expression +--- + +# $ifNull + +The `$ifNull` operator is used to evaluate an expression and return a specified value if the expression resolves to `null`. This operator is useful in scenarios where you want to provide a default value for fields that may not exist or may have `null` values. + +## Syntax + +```javascript +{ + $ifNull: [ , ] +} +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The expression to evaluate.| +| **``**| The value to return if the expression evaluates to `null`| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Default value for missing `store.manager` field + +To ensure that the `$staff.totalStaff.intern` field is always a number, you can use `$ifNull` to replace `null` values with `0`. + +```javascript +db.stores.aggregate([ + { + $project: { + name: 1, + interns: { $ifNull: ["$staff.totalStaff.intern", 0] } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "interns": 0 + }, + { + "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41", + "name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie", + "interns": 0 + }, + { + "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34", + "name": "Northwind Traders | Bed and Bath Place - West Oraland", + "interns": 0 + } +] + +``` diff --git a/api-reference/operators/conditional-expression/$switch.md b/api-reference/operators/conditional-expression/$switch.md new file mode 100644 index 0000000..b9e19da --- /dev/null +++ b/api-reference/operators/conditional-expression/$switch.md @@ -0,0 +1,204 @@ +--- +title: $switch +description: The $switch operator is used to evaluate a series of conditions and return a value based on the first condition that evaluates to true. +type: operators +category: conditional-expression +--- + +# $switch + +The `$switch` operator is used to evaluate a series of conditions and return a value based on the first condition that evaluates to true. This is useful when you need to implement complex conditional logic within aggregation pipelines. + +## Syntax + +```javascript +{ + $switch: { + branches: [ + { case: , then: }, + { case: , then: } + ], + default: + } +} +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **branches**| An array of documents, each containing| +| **case**| An expression that evaluates to either `true` or `false`| +| **then**| The expression to return if the associated `case` expression evaluates to `true`| +| **default**| The expression to return if none of the `case` expressions evaluate to `true`. This field is optional.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: To determine staff type based on full-time and part-time counts + +This query determines the type of staff based on their count. + +```javascript +db.stores.aggregate([{ + $project: { + name: 1, + staffType: { + $switch: { + branches: [{ + case: { + $eq: ["$staff.totalStaff.partTime", 0] + }, + then: "Only Full time" + }, + { + case: { + $eq: ["$staff.totalStaff.fullTime", 0] + }, + then: "Only Part time" + } + ], + default: "Both" + } + } + } + }, + // Limit the result to the first 3 documents + { + $limit: 3 + } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "staffType": "Only Full time" + }, + { + "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41", + "name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie", + "staffType": "Both" + }, + { + "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34", + "name": "Northwind Traders | Bed and Bath Place - West Oraland", + "staffType": "Both" + } +] +``` diff --git a/api-reference/operators/data-size/$binarysize.md b/api-reference/operators/data-size/$binarysize.md new file mode 100644 index 0000000..45e3b5b --- /dev/null +++ b/api-reference/operators/data-size/$binarysize.md @@ -0,0 +1,179 @@ +--- +title: $binarySize +description: The $binarySize operator is used to return the size of a binary data field. +type: operators +category: data-size +--- + +# $binarySize + +The `$binarySize` operator is used to return the size of a binary data field. This can be useful when dealing with binary data stored, such as images, files, or any other binary content. The argument for `$binarySize` should be a string, or a binary value. + +## Syntax + +```javascript +{ + $binarySize: "" +} +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **``**| The field for which you want to get the binary size.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculate the size of a string or binary data in bytes using $binarySize + +This query calculates the binary size of the name field for each document in the stores collection. + +```javascript +db.stores.aggregate([ + { + $project: { + name: 1, + dataSize: { + $binarySize: "$name" // Calculate the binary size of the string data + } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "name": "Contoso, Ltd. | Office Supply Deals - South Shana", + "dataSize": 49 + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "name": "Lakeshore Retail | Home Decor Hub - Franciscoton", + "dataSize": 48 + }, + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "dataSize": 50 + } +] +``` diff --git a/api-reference/operators/data-size/$bsonsize.md b/api-reference/operators/data-size/$bsonsize.md new file mode 100644 index 0000000..5d13780 --- /dev/null +++ b/api-reference/operators/data-size/$bsonsize.md @@ -0,0 +1,180 @@ +--- +title: $bsonSize +description: The $bsonSize operator returns the size of a document in bytes when encoded as BSON. +type: operators +category: data-size +--- + +# $bsonSize + +The `$bsonSize` operator is used to return the size of a document in bytes when encoded as BSON. It's useful for understanding the storage requirements of documents within your collections. The operator can be used within aggregation pipelines to calculate the size of documents and is helpful for optimizing storage and understanding performance implications. + +## Syntax + +```javascript +{ + $bsonSize: +} +``` + +### Parameters + +| Parameter | Description | +| --- | --- | +| **``**| Any valid expression that resolves to a document whose BSON size you want to calculate.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Calculate the total BSON-encoded size of a document in bytes using $bsonSize + +This query calculates the BSON size of the document. + +```javascript +db.stores.aggregate([ + { + $project: { + _id: 1, + name: 1, + documentSize: { + $bsonSize: "$$ROOT" //pass the whole document + } + } + }, + // Limit the result to the first 3 documents + { $limit: 3 } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "documentSize": 2226 + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "name": "Lakeshore Retail | Home Decor Hub - Franciscoton", + "documentSize": 1365 + }, + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "name": "Contoso, Ltd. | Office Supply Deals - South Shana", + "documentSize": 1882 + } +] +``` diff --git a/api-reference/operators/date-expression/$dateadd.md b/api-reference/operators/date-expression/$dateadd.md new file mode 100644 index 0000000..b5c8dd7 --- /dev/null +++ b/api-reference/operators/date-expression/$dateadd.md @@ -0,0 +1,227 @@ +--- +title: $dateAdd +description: The $dateAdd operator adds a specified number of time units (day, hour, month etc) to a date. +type: operators +category: date-expression +--- + +# $dateAdd + +The `$dateAdd` operator adds a specified number of time units to a date. It's useful in scenarios where you need to calculate future dates based on a given date and a time interval. + +## Syntax + +```javascript +$dateAdd: { + startDate: , + unit: , + amount: , + timezone: // Optional +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`startDate`** | The starting date for the addition operation. | +| **`unit`** | The unit of time to add. Valid units include: `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`, `millisecond`. | +| **`amount`** | The number of units to add. | +| **`timezone`** | Optional. The timezone to use for the operation. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Adding days to a date + +This query projects `eventName` and computes a `newEndDate` by adding 7 days to a date constructed from nested year, month, and day fields. The result is a simplified document showing the event name and its extended end date. + +```javascript +db.stores.aggregate([ + { $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } }, + { $unwind: "$promotionEvents" }, + { $unwind: "$promotionEvents.promotionalDates" }, + { + $project: { + eventName: 1, + newEndDate: { + $dateAdd: { + startDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.endDate.Year", + month: "$promotionEvents.promotionalDates.endDate.Month", + day: "$promotionEvents.promotionalDates.endDate.Day" + } + }, + unit: "day", + amount: 7 + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "newEndDate": "2024-10-06T00:00:00.000Z" + } +] +``` + +### Example 2: Adding months to a date + +This aggregation query projects the `eventName` and calculates a newStartDate by adding 1 month to a reconstructed start date from nested promotion fields. It helps determine an adjusted event start date based on the original schedule. This query returns each document’s eventName and a newStartDate that is 1 month after the original startDate from nested promotion event data. + +```javascript +db.stores.aggregate([ + { $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } }, + { $unwind: "$promotionEvents" }, + { $unwind: "$promotionEvents.promotionalDates" }, + { + $project: { + eventName: "$promotionEvents.eventName", + newStartDate: { + $dateAdd: { + startDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.startDate.Year", + month: "$promotionEvents.promotionalDates.startDate.Month", + day: "$promotionEvents.promotionalDates.startDate.Day" + } + }, + unit: "month", + amount: 1 + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "eventName": "Massive Markdown Mania", + "newStartDate": "2024-10-21T00:00:00.000Z" + } +] +``` diff --git a/api-reference/operators/date-expression/$datediff.md b/api-reference/operators/date-expression/$datediff.md new file mode 100644 index 0000000..a62c1e0 --- /dev/null +++ b/api-reference/operators/date-expression/$datediff.md @@ -0,0 +1,209 @@ +--- +title: $dateDiff +description: The $dateDiff operator calculates the difference between two dates in various units such as years, months, days, etc. +type: operators +category: date-expression +--- + +# $dateDiff + +The `$dateDiff` operator calculates the difference between two dates in various units such as years, months, days, etc. It's useful for determining the duration between two timestamps in your dataset. + +## Syntax + +```javascript +$dateDiff: { + startDate: , + endDate: , + unit: , + timezone: , // Optional + startOfWeek: // Optional +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`startDate`**| The beginning date for the calculation.| +| **`endDate`**| The ending date for the calculation.| +| **`unit`**| The unit of time to measure the difference. Valid values include: `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`, `millisecond`.| +| **`timezone`**| Optional. The timezone to use for the calculation.| +| **`startOfWeek`**| Optional. The starting day of the week. Valid values are: `Sunday`, `Monday`, `Tuesday`, `Wednesday`, `Thursday`, `Friday`, `Saturday`.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +## Example 1: Calculate duration in days between two dates + +This query uses `$dateDiff` to compute the number of units (e.g., days, months) between two date fields. It helps measure durations like event length or time since a given date. This query returns the durationInDays along with other fields for the specified `stores` document. + +```javascript +db.stores.aggregate([ + { $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } }, + { $unwind: "$promotionEvents" }, + { + $project: { + eventName: "$promotionEvents.eventName", + startDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.startDate.Year", + month: "$promotionEvents.promotionalDates.startDate.Month", + day: "$promotionEvents.promotionalDates.startDate.Day" + } + }, + endDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.endDate.Year", + month: "$promotionEvents.promotionalDates.endDate.Month", + day: "$promotionEvents.promotionalDates.endDate.Day" + } + }, + durationInDays: { + $dateDiff: { + startDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.startDate.Year", + month: "$promotionEvents.promotionalDates.startDate.Month", + day: "$promotionEvents.promotionalDates.startDate.Day" + } + }, + endDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.endDate.Year", + month: "$promotionEvents.promotionalDates.endDate.Month", + day: "$promotionEvents.promotionalDates.endDate.Day" + } + }, + unit: "day" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "eventName": "Massive Markdown Mania", + "startDate": "2024-09-21T00:00:00.000Z", + "endDate": "2024-09-29T00:00:00.000Z", + "durationInDays": 8 + } +] +``` diff --git a/api-reference/operators/date-expression/$datefromparts.md b/api-reference/operators/date-expression/$datefromparts.md new file mode 100644 index 0000000..5235fed --- /dev/null +++ b/api-reference/operators/date-expression/$datefromparts.md @@ -0,0 +1,192 @@ +--- +title: $dateFromParts +description: The $dateFromParts operator constructs a date from individual components. +type: operators +category: date-expression +--- + +# $dateFromParts + +The `$dateFromParts` operator constructs a date from individual components such as year, month, day, hour, minute, second, and millisecond. This operator can be useful when dealing with data that stores date components separately. + +## Syntax + +```javascript +{ + $dateFromParts: { + year: < year > , + month: < month > , + day: < day > , + hour: < hour > , + minute: < minute > , + second: < second > , + millisecond: < millisecond > , + timezone: < timezone > + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`year`** | The year component of the date. | +| **`month`** | The month component of the date. | +| **`day`** | The day component of the date. | +| **`hour`** | The hour component of the date. | +| **`minute`** | The minute component of the date. | +| **`second`** | The second component of the date. | +| **`millisecond`** | The millisecond component of the date. | +| **`timezone`** | Optional. A timezone specification. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Constructing a start date + +This query constructs precise startDate and endDate values from nested fields using `$dateFromParts`, then calculates the event duration in days. It helps standardize and analyze event timelines stored in fragmented date formats. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $unwind: "$promotionEvents" + }, + { + $project: { + _id: 1, + startDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.startDate.Year", + month: "$promotionEvents.promotionalDates.startDate.Month", + day: "$promotionEvents.promotionalDates.startDate.Day" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "startDate": "2024-09-21T00:00:00.000Z" + } +] +``` diff --git a/api-reference/operators/date-expression/$datefromstring.md b/api-reference/operators/date-expression/$datefromstring.md new file mode 100644 index 0000000..e00d593 --- /dev/null +++ b/api-reference/operators/date-expression/$datefromstring.md @@ -0,0 +1,231 @@ +--- +title: $dateFromString +description: The $dateDiff operator converts a date/time string to a date object. +type: operators +category: date-expression +--- + +# $dateFromString + +The `$dateFromString` operator is used to convert a date/time string to a date object. This operation can be useful when dealing with string representations of dates that need to be manipulated or queried as date objects. + +## Syntax + +```javascript +{ + $dateFromString: { + dateString: < string > , + format: < string > , + timezone: < string > , + onError: < expression > , + onNull: < expression > + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateString`** | The date/time string to convert to a date object. | +| **`format`** | (Optional) The date format specification of the `dateString`. | +| **`timezone`** | (Optional) The timezone to use to format the date. | +| **`onError`** | (Optional) The value to return if an error occurs while parsing the `dateString`. | +| **`onNull`** | (Optional) The value to return if the `dateString` is `null` or missing. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Convert promotional event dates to ISO dates + +This query constructs full ISO date strings from individual year, month, and day fields using `$concat` and converts them to startDate and endDate using `$dateFromString`. It’s useful when date components are stored separately in documents. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $unwind: "$promotionEvents" + }, + { + $project: { + eventName: "$promotionEvents.eventName", + startDate: { + $dateFromString: { + dateString: { + $concat: [ + { $toString: "$promotionEvents.promotionalDates.startDate.Year" }, + "-", + { + $cond: { + if: { $lt: ["$promotionEvents.promotionalDates.startDate.Month", 10] }, + then: { $concat: ["0", { $toString: "$promotionEvents.promotionalDates.startDate.Month" }] }, + else: { $toString: "$promotionEvents.promotionalDates.startDate.Month" } + } + }, + "-", + { + $cond: { + if: { $lt: ["$promotionEvents.promotionalDates.startDate.Day", 10] }, + then: { $concat: ["0", { $toString: "$promotionEvents.promotionalDates.startDate.Day" }] }, + else: { $toString: "$promotionEvents.promotionalDates.startDate.Day" } + } + } + ] + } + } + }, + endDate: { + $dateFromString: { + dateString: { + $concat: [ + { $toString: "$promotionEvents.promotionalDates.endDate.Year" }, + "-", + { + $cond: { + if: { $lt: ["$promotionEvents.promotionalDates.endDate.Month", 10] }, + then: { $concat: ["0", { $toString: "$promotionEvents.promotionalDates.endDate.Month" }] }, + else: { $toString: "$promotionEvents.promotionalDates.endDate.Month" } + } + }, + "-", + { + $cond: { + if: { $lt: ["$promotionEvents.promotionalDates.endDate.Day", 10] }, + then: { $concat: ["0", { $toString: "$promotionEvents.promotionalDates.endDate.Day" }] }, + else: { $toString: "$promotionEvents.promotionalDates.endDate.Day" } + } + } + ] + } + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "eventName": "Massive Markdown Mania", + "startDate": "2024-09-21T00:00:00.000Z", + "endDate": "2024-09-29T00:00:00.000Z" + } +] +``` diff --git a/api-reference/operators/date-expression/$datesubtract.md b/api-reference/operators/date-expression/$datesubtract.md new file mode 100644 index 0000000..f119639 --- /dev/null +++ b/api-reference/operators/date-expression/$datesubtract.md @@ -0,0 +1,180 @@ +--- +title: $dateSubtract +description: The $dateSubtract operator subtracts a specified amount of time from a date. +type: operators +category: date-expression +--- + +# $dateSubtract + +The `$dateSubtract` operator subtracts a specified time unit from a date. It's useful for calculating past dates or intervals in aggregation pipelines. + +## Syntax + +```javascript +{ + $dateSubtract: { + startDate: , + unit: "", + amount: , + timezone: "" // optional + } +} +``` + +## Parameters + +| Parameter | Description | +| --------------- | ------------------------------------------------ | +| **`startDate`** | The date expression to subtract from. | +| **`unit`** | The time unit to subtract (for example, "day", "hour"). | +| **`amount`** | The amount of the time unit to subtract. | +| **`timezone`** | *(Optional)* Timezone for date calculation. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Subtract seven days + +This query calculates the date one week before the `lastUpdated` field. This query uses `$dateSubtract` to calculate the date exactly seven days before the `storeOpeningDate` timestamp. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + dateOneWeekAgo: { + $dateSubtract: { + startDate: "$storeOpeningDate", + unit: "day", + amount: 7 + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "dateOneWeekAgo": "2024-08-29T11:50:06.549Z" + } +] +``` diff --git a/api-reference/operators/date-expression/$datetoparts.md b/api-reference/operators/date-expression/$datetoparts.md new file mode 100644 index 0000000..7abbe7e --- /dev/null +++ b/api-reference/operators/date-expression/$datetoparts.md @@ -0,0 +1,223 @@ +--- +title: $dateToParts +description: The $dateToParts operator decomposes a date into its individual parts such as year, month, day, and more. +type: operators +category: date-expression +--- + +# $dateToParts + +The `$dateToParts` operator is used to extract individual components (Year, Month, Day, Hour, Minute, Second, Millisecond, etc.) from a date object. The operator is useful for scenarios where manipulation or analysis of specific date parts is required, such as sorting, filtering, or aggregating data based on individual date components. + +## Syntax + +```javascript +$dateToParts: { + date: , + timezone: , // optional + iso8601: // optional +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`date`** | The date expression to extract parts from. | +| **`timezone`** | Optional. Specifies the timezone for the date. Defaults to UTC if not provided. | +| **`iso8601`** | Optional. If true, the operator uses ISO 8601 week date calendar system. Defaults to false. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extracting date parts from a field + +This query uses `$dateToParts` to break down the `lastUpdated` date into components like year, month, day, and time. It helps in analyzing or transforming individual parts of a date for further processing. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + dateParts: { + $dateToParts: { + date: "$lastUpdated" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "dateParts": { + "year": 2024, + "month": 12, + "day": 4, + "hour": 11, + "minute": 50, + "second": 6, + "millisecond": 0 + } + } +] +``` + +### Example 2: Using timezone + +This query extracts the `lastUpdated` timestamp of a specific document and breaks it into date parts like year, month, day, and hour using $dateToParts. Including the "America/New_York" timezone permits the breakdown, reflects the local time instead of UTC. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + datePartsWithTimezone: { + $dateToParts: { + date: "$lastUpdated", + timezone: "America/New_York" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "datePartsWithTimezone": { + "year": 2024, + "month": 12, + "day": 4, + "hour": 6, + "minute": 50, + "second": 6, + "millisecond": 0 + } + } +] +``` diff --git a/api-reference/operators/date-expression/$datetostring.md b/api-reference/operators/date-expression/$datetostring.md new file mode 100644 index 0000000..33a0b69 --- /dev/null +++ b/api-reference/operators/date-expression/$datetostring.md @@ -0,0 +1,225 @@ +--- +title: $dateToString +description: The $dateToString operator converts a date object into a formatted string. +type: operators +category: date-expression +--- + +# $dateToString + +The `$dateToString` operator is used to convert a date object to a string in a specified format. It's commonly used in aggregation pipelines to format date fields for reporting, querying, or display purposes. This operator is highly versatile and allows you to define custom date formats. + +## Syntax + +```javascript +{ + $dateToString: { + format: "", + date: , + timezone: "", + onNull: "" + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`format`** | A string that specifies the format of the output date. | +| **`date`** | The date expression to format. | +| **`timezone`** | (Optional) A string that specifies the timezone. Defaults to UTC if not provided. | +| **`onNull`** | (Optional) A value to return if the `date` field is `null` or missing. | + +## Format Specifiers + +| Symbol | Meaning | +| ------ | ------------------------ | +| `%Y` | Year (four digits) | +| `%m` | Month (two digits) | +| `%d` | Day of month (two digits) | +| `%H` | Hour (24-hour, two digits) | +| `%M` | Minute (two digits) | +| `%S` | Second (two digits) | +| `%L` | Millisecond (three digits) | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Formatting a date field to an ISO-like string + +This query uses `$dateToString` operator to format the `lastUpdated` timestamp into a `YYYY-MM-DD` string. It helps present dates in a readable format suitable for logs, reports, or UI. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + formattedDate: { + $dateToString: { + format: "%Y-%m-%d", + date: "$lastUpdated" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "formattedDate": "2024-12-04" + } +] +``` + +### Example 2: Handling Null Values + +This query formats the nonexistent field `lastUpdated_new` timestamp as a `YYYY-MM-DD` string using `$dateToString`. Considering the date is missing or null, it substitutes a fallback string "No date available" via the onNull option. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + formattedDateOrDefault: { + $dateToString: { + format: "%Y-%m-%d", + date: "$lastUpdated_new", // field doesn't exist + onNull: "No date available" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "formattedDateOrDefault": "No date available" + } +] +``` diff --git a/api-reference/operators/date-expression/$datetrunc.md b/api-reference/operators/date-expression/$datetrunc.md new file mode 100644 index 0000000..929a60e --- /dev/null +++ b/api-reference/operators/date-expression/$datetrunc.md @@ -0,0 +1,212 @@ +--- +title: $dateTrunc +description: The $dateTrunc operator truncates a date to a specified unit. +type: operators +category: date-expression +--- + +# $dateTrunc + +The `$dateTrunc` expression operator truncates a date to the nearest specified unit (for example, hour, day, month). It's useful when working with time-series data or when grouping data by specific time intervals. This operator can be used to simplify and standardize date calculations. + +## Syntax + +```javascript + $dateTrunc: { + date: , + unit: "", + binSize: , // optional + timezone: "", // optional + startOfWeek: "" // optional (used when unit is "week") + } +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`date`** | The date to truncate. | +| **`unit`** | The unit to truncate the date to. Supported values include `year`, `month`, `week`, `day`, `hour`, `minute`, `second`, and `millisecond`. | +| **`binSize`** | (Optional) The size of each bin for truncation. For example, if `binSize` is 2 and `unit` is `hour`, the date is truncated to every 2 hours. | +| **`timezone`** | (Optional) The timezone to use for truncation. Defaults to UTC if not specified. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Truncate to the day + +This query uses `$dateTrunc` to truncate the `lastUpdated` timestamp to the start of the day (00:00:00) in UTC. The operator is useful for grouping or comparing data by calendar day regardless of time. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + truncatedToDay: { + $dateTrunc: { + date: "$lastUpdated", + unit: "day" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "truncatedToDay": "2024-11-29T00:00:00.000Z" + } +] +``` + +### Example 2: Truncate to the start of the week + +This query uses `$dateTrunc` to round the `lastUpdated` timestamp down to the start of its week. It specifies Monday as the start of the week to ensure consistent calendar alignment. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + truncatedToWeek: { + $dateTrunc: { + date: "$lastUpdated", + unit: "week", + startOfWeek: "Monday" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "truncatedToWeek": "2024-11-25T00:00:00.000Z" + } +] +``` diff --git a/api-reference/operators/date-expression/$dayofmonth.md b/api-reference/operators/date-expression/$dayofmonth.md new file mode 100644 index 0000000..eae31ae --- /dev/null +++ b/api-reference/operators/date-expression/$dayofmonth.md @@ -0,0 +1,166 @@ +--- +title: $dayOfMonth +description: The $dayOfMonth operator extracts the day of the month from a date. +type: operators +category: date-expression +--- + +# $dayOfMonth + +The `$dayOfMonth` operator extracts the day of the month (1–31) from a date value. It's useful for grouping or filtering documents based on the day of the month. + +## Syntax + +```javascript +{ + $dayOfMonth: +} +``` + +## Parameters + +| Parameter | Description | +| ---------------------- | --------------------------------------------------------------- | +| **``** | The date expression from which to extract the day of the month. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract day of the month + +This query uses the `$dayOfMonth` operator to extract the day of the month (1–31) from the `lastUpdated` timestamp and isolates the date component of the field for reporting or grouping. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + dayOfMonth: { $dayOfMonth: "$lastUpdated" } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "dayOfMonth": "4" + } +] +``` diff --git a/api-reference/operators/date-expression/$dayofweek.md b/api-reference/operators/date-expression/$dayofweek.md new file mode 100644 index 0000000..5cbd029 --- /dev/null +++ b/api-reference/operators/date-expression/$dayofweek.md @@ -0,0 +1,166 @@ +--- +title: $dayOfWeek +description: The $dayOfWeek operator extracts the day of the week from a date. +type: operators +category: date-expression +--- + +# $dayOfWeek + +The `$dayOfWeek` operator extracts the day of the week from a date value, where 1 represents Sunday and 7 represents Saturday. It's useful for grouping or filtering documents based on the day of the week. + +## Syntax + +```javascript +{ + $dayOfWeek: +} +``` + +## Parameters + +| Parameter | Description | +| ---------------------- | -------------------------------------------------------------- | +| **``** | The date expression from which to extract the day of the week. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract day of the week + +This query uses the `$dayOfWeek` operator to extract the day of the week from the `lastUpdated` timestamp. The returned value ranges from 1 (Sunday) to 7 (Saturday), based on ISO-8601 ordering. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + dayOfWeek: { $dayOfWeek: "$lastUpdated" } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "dayOfWeek": "4" + } +] +``` diff --git a/api-reference/operators/date-expression/$dayofyear.md b/api-reference/operators/date-expression/$dayofyear.md new file mode 100644 index 0000000..5c309c7 --- /dev/null +++ b/api-reference/operators/date-expression/$dayofyear.md @@ -0,0 +1,170 @@ +--- +title: $dayOfYear +description: The $dayOfYear operator extracts the day of the year from a date. +type: operators +category: date-expression +--- + +# $dayOfYear + +The `$dayOfYear` operator extracts the day of the year from a date value, where 1 represents January 1. It's useful for grouping or filtering documents based on the day of the year. + +## Syntax + +```javascript +{ + $dayOfYear: +} +``` + +## Parameters + +| Parameter | Description | +| ---------------------- | -------------------------------------------------------------- | +| **``** | The date expression from which to extract the day of the year. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract day of the year + +This query uses the `$dayOfYear` operator to extract the ordinal day of the year (1–366) from the `lastUpdated` timestamp. + +```javascript +db.stores.aggregate([ + { + $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } + }, + { + $project: { + _id: 0, + dayOfYear: { $dayOfYear: "$lastUpdated" } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "dayOfYear": 339 + } +] +``` + +```json +{ "dayOfYear": 339 } +``` diff --git a/api-reference/operators/date-expression/$hour.md b/api-reference/operators/date-expression/$hour.md new file mode 100644 index 0000000..fdc0ab3 --- /dev/null +++ b/api-reference/operators/date-expression/$hour.md @@ -0,0 +1,170 @@ +--- +title: $hour +description: The $hour operator returns the hour portion of a date as a number between 0 and 23. +type: operators +category: date-expression +--- + +# $hour + +The `$hour` operator returns the hour portion of a date as a number between 0 and 23. The operator accepts a date expression that resolves to a Date, Timestamp, or ObjectId. + +## Syntax + +```javascript +{ + $hour: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | An expression that resolves to a Date, Timestamp, or ObjectId. If the expression resolves to null or is missing, `$hour` returns null. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract hour from current date + +This query extracts the `hour` from the current date and time. + +```javascript +db.stores.aggregate([ + { $match: { "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } }, + { + $project: { + name: 1, + storeOpeningDate: 1, + currentHour: { $hour: new Date() }, + documentHour: { $hour: "$storeOpeningDate" } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "name": "Relecloud | Toy Collection - North Jaylan", + "storeOpeningDate": "2024-09-05T11:50:06.549Z", + "currentHour": 12, + "documentHour": 11 + } +] +``` diff --git a/api-reference/operators/date-expression/$isodayofweek.md b/api-reference/operators/date-expression/$isodayofweek.md new file mode 100644 index 0000000..4bb645d --- /dev/null +++ b/api-reference/operators/date-expression/$isodayofweek.md @@ -0,0 +1,232 @@ +--- +title: $isoDayOfWeek +description: The $isoDayOfWeek operator returns the weekday number in ISO 8601 format, ranging from 1 (Monday) to 7 (Sunday). +type: operators +category: date-expression +--- + +# $isoDayOfWeek + +The `$isoDayOfWeek` operator returns the weekday number in ISO 8601 format, ranging from 1 (Monday) to 7 (Sunday). The operator accepts a date expression that resolves to a Date, Timestamp, or ObjectId. + +## Syntax + +```javascript +{ + $isoDayOfWeek: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | An expression that resolves to a Date, Timestamp, or ObjectId. If the expression resolves to null or is missing, `$isoDayOfWeek` returns null. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Analyze promotion events by day of week + +This query reviews promotion events to see which days of the week they started on. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { $unwind: "$promotionEvents" }, + { + $project: { + eventName: "$promotionEvents.eventName", + startDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.startDate.Year", + month: "$promotionEvents.promotionalDates.startDate.Month", + day: "$promotionEvents.promotionalDates.startDate.Day" + } + } + } + }, + { + $group: { + _id: { $isoDayOfWeek: "$startDate" }, + eventCount: { $sum: 1 }, + events: { $push: "$eventName" } + } + }, + { + $project: { + _id: 1, + dayName: { + $switch: { + branches: [ + { case: { $eq: ["$_id", 1] }, then: "Monday" }, + { case: { $eq: ["$_id", 2] }, then: "Tuesday" }, + { case: { $eq: ["$_id", 3] }, then: "Wednesday" }, + { case: { $eq: ["$_id", 4] }, then: "Thursday" }, + { case: { $eq: ["$_id", 5] }, then: "Friday" }, + { case: { $eq: ["$_id", 6] }, then: "Saturday" }, + { case: { $eq: ["$_id", 7] }, then: "Sunday" } + ] + } + }, + eventCount: 1, + events: 1 + } + }, + { $sort: { "_id": 1 } } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": 1, + "eventCount": 1, + "events": ["Super Sale Spectacular"], + "dayName": "Monday" + }, + { + "_id": 2, + "eventCount": 1, + "events": ["Discount Delight Days"], + "dayName": "Tuesday" + }, + { + "_id": 3, + "eventCount": 1, + "events": ["Fantastic Deal Days"], + "dayName": "Wednesday" + }, + { + "_id": 4, + "eventCount": 1, + "events": ["Massive Markdown Mania"], + "dayName": "Thursday" + }, + { + "_id": 6, + "eventCount": 1, + "events": ["Major Bargain Bash"], + "dayName": "Saturday" + }, + { + "_id": 7, + "eventCount": 1, + "events": ["Grand Deal Days"], + "dayName": "Sunday" + } +] +``` diff --git a/api-reference/operators/date-expression/$isoweek.md b/api-reference/operators/date-expression/$isoweek.md new file mode 100644 index 0000000..b9ee047 --- /dev/null +++ b/api-reference/operators/date-expression/$isoweek.md @@ -0,0 +1,218 @@ +--- +title: $isoWeek +description: The $isoWeek operator returns the week number of the year in ISO 8601 format, ranging from 1 to 53. +type: operators +category: date-expression +--- + +# $isoWeek + +The `$isoWeek` operator returns the week number of the year in ISO 8601 format, ranging from 1 to 53. The operator accepts a date expression that resolves to a Date, Timestamp, or ObjectId. In ISO 8601, weeks start on Monday and the first week of the year is the week that contains the first Thursday of the year. + +## Syntax + +```javascript +{ + $isoWeek: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | An expression that resolves to a Date, Timestamp, or ObjectId. If the expression resolves to null or is missing, `$isoWeek` returns null. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Get ISO week number for promotion events + +This query extracts the ISO week number for promotion event start dates. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { $unwind: "$promotionEvents" }, + { + $project: { + eventName: "$promotionEvents.eventName", + startDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.startDate.Year", + month: "$promotionEvents.promotionalDates.startDate.Month", + day: "$promotionEvents.promotionalDates.startDate.Day" + } + } + } + }, + { + $project: { + eventName: 1, + startDate: 1, + isoWeekNumber: { $isoWeek: "$startDate" }, + year: { $year: "$startDate" } + } + } +]) +``` + +This query returns the following results: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Massive Markdown Mania", + "startDate": "2023-06-29T00:00:00.000Z", + "isoWeekNumber": 26, + "year": 2023 + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Fantastic Deal Days", + "startDate": "2023-09-27T00:00:00.000Z", + "isoWeekNumber": 39, + "year": 2023 + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Discount Delight Days", + "startDate": "2023-12-26T00:00:00.000Z", + "isoWeekNumber": 52, + "year": 2023 + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Super Sale Spectacular", + "startDate": "2024-03-25T00:00:00.000Z", + "isoWeekNumber": 13, + "year": 2024 + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Grand Deal Days", + "startDate": "2024-06-23T00:00:00.000Z", + "isoWeekNumber": 25, + "year": 2024 + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Major Bargain Bash", + "startDate": "2024-09-21T00:00:00.000Z", + "isoWeekNumber": 38, + "year": 2024 + } +] +``` diff --git a/api-reference/operators/date-expression/$isoweekyear.md b/api-reference/operators/date-expression/$isoweekyear.md new file mode 100644 index 0000000..c336988 --- /dev/null +++ b/api-reference/operators/date-expression/$isoweekyear.md @@ -0,0 +1,201 @@ +--- +title: $isoWeekYear +description: The $isoWeekYear operator returns the year number in ISO 8601 format, which can differ from the calendar year for dates at the beginning or end of the year. +type: operators +category: date-expression +--- + +# $isoWeekYear + +The `$isoWeekYear` operator returns the year number in ISO 8601 format. The ISO week-numbering year can differ from the calendar year for dates at the beginning or end of the year. The ISO week year is the year that contains the Thursday of the week in question. + +## Syntax + +```javascript +{ + $isoWeekYear: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | An expression that resolves to a Date, Timestamp, or ObjectId. If the expression resolves to null or is missing, `$isoWeekYear` returns null. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Compare calendar year vs ISO week year + +This query demonstrates the difference between calendar year and ISO week year, especially for dates near year boundaries. + +```javascript +db.stores.aggregate([ + { $match: {_id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { $unwind: "$promotionEvents" }, + { + $project: { + eventName: "$promotionEvents.eventName", + startDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.startDate.Year", + month: "$promotionEvents.promotionalDates.startDate.Month", + day: "$promotionEvents.promotionalDates.startDate.Day" + } + }, + endDate: { + $dateFromParts: { + year: "$promotionEvents.promotionalDates.endDate.Year", + month: "$promotionEvents.promotionalDates.endDate.Month", + day: "$promotionEvents.promotionalDates.endDate.Day" + } + } + } + }, + { + $project: { + eventName: 1, + startDate: 1, + endDate: 1, + startCalendarYear: { $year: "$startDate" }, + startISOWeekYear: { $isoWeekYear: "$startDate" }, + endCalendarYear: { $year: "$endDate" }, + endISOWeekYear: { $isoWeekYear: "$endDate" }, + yearDifference: { + $ne: [{ $year: "$startDate" }, { $isoWeekYear: "$startDate" }] + } + } + }, + { $match: {"eventName": "Discount Delight Days" } } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Discount Delight Days", + "startDate": "2023-12-26T00:00:00.000Z", + "endDate": "2024-01-05T00:00:00.000Z", + "startCalendarYear": 2023, + "startISOWeekYear": Long("2023"), + "endCalendarYear": 2024, + "endISOWeekYear": Long("2024"), + "yearDifference": true + } +] +``` diff --git a/api-reference/operators/date-expression/$millisecond.md b/api-reference/operators/date-expression/$millisecond.md new file mode 100644 index 0000000..47194df --- /dev/null +++ b/api-reference/operators/date-expression/$millisecond.md @@ -0,0 +1,170 @@ +--- +title: $millisecond +description: The $millisecond operator extracts the milliseconds portion from a date value. +type: operators +category: date-expression +--- + +# $millisecond + +The `$millisecond` operator extracts the milliseconds portion from a date value, returning a number between 0 and 999. This operator is useful for precise timestamp analysis and filtering operations that require millisecond-level granularity. + +## Syntax + +```javascript +{ + $millisecond: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | An expression that resolves to a Date, a Timestamp, or an ObjectId. If the expression resolves to `null` or is missing, `$millisecond` returns `null`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract milliseconds from store opening date + +This query extracts the milliseconds portion from the store opening date. + +```javascript +db.stores.aggregate([ + { $match: {_id: "905d1939-e03a-413e-a9c4-221f74055aac"} }, + { + $project: { + name: 1, + storeOpeningDate: 1, + openingMilliseconds: { + $millisecond: "$storeOpeningDate" + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "storeOpeningDate": ISODate("2024-09-26T22:55:25.779Z"), + "openingMilliseconds": 779 + } +] +``` diff --git a/api-reference/operators/date-expression/$minute.md b/api-reference/operators/date-expression/$minute.md new file mode 100644 index 0000000..028b078 --- /dev/null +++ b/api-reference/operators/date-expression/$minute.md @@ -0,0 +1,170 @@ +--- +title: $minute +description: The $minute operator extracts the minute portion from a date value. +type: operators +category: date-expression +--- + +# $minute + +The `$minute` operator extracts the minute portion from a date value, returning a number between 0 and 59. This operator is commonly used for time-based analysis and scheduling operations. + +## Syntax + +```javascript +{ + $minute: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | An expression that resolves to a Date, a Timestamp, or an ObjectId. If the expression resolves to `null` or is missing, `$minute` returns `null`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract minutes from store opening date + +This query extracts the minute portion from the store opening date to analyze opening time patterns. + +```javascript +db.stores.aggregate([ + { $match: {_id: "905d1939-e03a-413e-a9c4-221f74055aac"} }, + { + $project: { + name: 1, + storeOpeningDate: 1, + openingMinute: { + $minute: "$storeOpeningDate" + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "storeOpeningDate": ISODate("2024-09-26T22:55:25.779Z"), + "openingMinute": 55 + } +] +``` diff --git a/api-reference/operators/date-expression/$month.md b/api-reference/operators/date-expression/$month.md new file mode 100644 index 0000000..b59492f --- /dev/null +++ b/api-reference/operators/date-expression/$month.md @@ -0,0 +1,189 @@ +--- +title: $month +description: The $month operator extracts the month portion from a date value. +type: operators +category: date-expression +--- + +# $month + +The `$month` operator extracts the month portion from a date value, returning a number between 1 and 12, where 1 represents January and 12 represents December. This operator is essential for seasonal analysis and monthly reporting. + +## Syntax + +```javascript +{ + $month: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | An expression that resolves to a Date, a Timestamp, or an ObjectId. If the expression resolves to `null` or is missing, `$month` returns `null`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract month from store opening date + +This query extracts the month portion from the store opening date to analyze seasonal opening patterns. + +```javascript +db.stores.aggregate([ + { $match: {_id: "905d1939-e03a-413e-a9c4-221f74055aac"} }, + { + $project: { + name: 1, + storeOpeningDate: 1, + openingMonth: { + $month: "$storeOpeningDate" + }, + openingMonthName: { + $switch: { + branches: [ + { case: { $eq: [{ $month: "$storeOpeningDate" }, 1] }, then: "January" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 2] }, then: "February" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 3] }, then: "March" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 4] }, then: "April" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 5] }, then: "May" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 6] }, then: "June" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 7] }, then: "July" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 8] }, then: "August" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 9] }, then: "September" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 10] }, then: "October" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 11] }, then: "November" }, + { case: { $eq: [{ $month: "$storeOpeningDate" }, 12] }, then: "December" } + ] + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "storeOpeningDate": "2024-12-30T22:55:25.779Z", + "openingMonth": 12, + "openingMonthName": "December" + } +] +``` diff --git a/api-reference/operators/date-expression/$second.md b/api-reference/operators/date-expression/$second.md new file mode 100644 index 0000000..de4191e --- /dev/null +++ b/api-reference/operators/date-expression/$second.md @@ -0,0 +1,170 @@ +--- +title: $second +description: The $second operator extracts the seconds portion from a date value. +type: operators +category: date-expression +--- + +# $second + +The `$second` operator extracts the seconds portion from a date value, returning a number between 0 and 59. This operator is useful for precise timestamp analysis and time-sensitive operations that require second-level granularity. + +## Syntax + +```javascript +{ + $second: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | An expression that resolves to a Date, a Timestamp, or an ObjectId. If the expression resolves to `null` or is missing, `$second` returns `null`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract seconds from store opening date + +This query extracts the seconds portion from the store opening date for precise timing analysis. + +```javascript +db.stores.aggregate([ + { $match: {_id: "905d1939-e03a-413e-a9c4-221f74055aac"} }, + { + $project: { + name: 1, + storeOpeningDate: 1, + openingSecond: { + $second: "$storeOpeningDate" + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "storeOpeningDate": ISODate("2024-12-30T22:55:25.779Z"), + "openingSecond": 25 + } +] +``` diff --git a/api-reference/operators/date-expression/$week.md b/api-reference/operators/date-expression/$week.md new file mode 100644 index 0000000..16141d3 --- /dev/null +++ b/api-reference/operators/date-expression/$week.md @@ -0,0 +1,231 @@ +--- +title: $week +description: The $week operator returns the week number for a date as a value between 0 and 53. +type: operators +category: date-expression +--- + +# $week + +The `$week` operator returns the week number for a date as a value between 0 and 53. Week 0 begins on January 1, and subsequent weeks begin on Sundays. If the date is null or missing, `$week` returns null. + +## Syntax + +The syntax for the `$week` operator is as follows: + +```javascript +{ + $week: +} +``` + +Or with timezone specification + +```javascript +{ + $week: { + date: , + timezone: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | Any expression that resolves to a Date, Timestamp, or ObjectId. | +| **`timezone`** | Optional. The timezone to use for the calculation. Can be an Olson Timezone Identifier (for example, "America/New_York") or a UTC offset (for example, "+0530"). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Get week number for store opening date + +This query extracts the week number from the store opening date. + +```javascript +db.stores.aggregate([ + { $match: { _id: "905d1939-e03a-413e-a9c4-221f74055aac" } }, + { + $project: { + name: 1, + storeOpeningDate: 1, + openingWeek: { $week: { $toDate: "$storeOpeningDate" } } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "storeOpeningDate": ISODate("2024-12-30T22:55:25.779Z"), + "openingWeek": 52 + } +] +``` + +### Example 2: Group stores by opening week + +This query groups stores by the week they were opened for analysis. + +```javascript +db.stores.aggregate([ + { + $project: { + name: 1, + openingWeek: { $week: { $toDate: "$storeOpeningDate" } }, + openingYear: { $year: { $toDate: "$storeOpeningDate" } } + } + }, + { + $group: { + _id: { week: "$openingWeek", year: "$openingYear" }, + storeCount: { $sum: 1 }, + stores: { $push: "$name" } + } + }, + { $sort: { "_id.year": 1, "_id.week": -1 } }, + { $limit : 3 } ]) +``` + +This query returns the following results: + +```json +[ + { + "_id": { "week": 40, "year": 2021 }, + "storeCount": 1, + "stores": [ "First Up Consultants | Bed and Bath Center - South Amir" ] + }, + { + "_id": { "week": 52, "year": 2024 }, + "storeCount": 1, + "stores": [ "Trey Research | Home Office Depot - Lake Freeda" ] + }, + { + "_id": { "week": 50, "year": 2024 }, + "storeCount": 2, + "stores": [ + "Fourth Coffee | Paper Product Bazaar - Jordanechester", + "Adatum Corporation | Pet Supply Center - West Cassie" + ] + } +] +``` diff --git a/api-reference/operators/date-expression/$year.md b/api-reference/operators/date-expression/$year.md new file mode 100644 index 0000000..6af94e1 --- /dev/null +++ b/api-reference/operators/date-expression/$year.md @@ -0,0 +1,220 @@ +--- +title: $year +description: The $year operator returns the year for a date as a four-digit number. +type: operators +category: date-expression +--- + +# $year + +The `$year` operator returns the year for a date as a four-digit number (for example, 2024). If the date is null or missing, `$year` returns null. + +## Syntax + +The syntax for the `$year` operator is as follows: + +```javascript +{ + $year: +} +``` + +Or with timezone specification + +```javascript +{ + $year: { + date: , + timezone: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`dateExpression`** | Any expression that resolves to a Date, Timestamp, or ObjectId. | +| **`timezone`** | Optional. The timezone to use for the calculation. Can be an Olson Timezone Identifier (for example, "America/New_York") or a UTC offset (for example, "+0530"). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract year from store opening date + +This query extracts the year when the store was opened. + +```javascript +db.stores.aggregate([ + { $match: { _id: "905d1939-e03a-413e-a9c4-221f74055aac" } }, + { + $project: { + name: 1, + storeOpeningDate: 1, + openingYear: { $year: { $toDate: "$storeOpeningDate" } } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "storeOpeningDate": "2024-12-30T22:55:25.779Z", + "openingYear": 2024 + } +] +``` + +### Example 2: Find stores opened in specific year + +This query retrieves all stores that were opened in 2021. + +```javascript +db.stores.aggregate([ + { + $match: { + $expr: { + $eq: [{ $year: { $toDate: "$storeOpeningDate" } }, 2021] + } + } + }, + { + $project: { + name: 1, + city: 1, + openingYear: { $year: { $toDate: "$storeOpeningDate" } }, + storeOpeningDate: 1 + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "city": "South Amir", + "storeOpeningDate": "2021-10-03T00:00:00.000Z", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "openingYear": 2021 + } +] +``` diff --git a/api-reference/operators/element-query/$exists.md b/api-reference/operators/element-query/$exists.md new file mode 100644 index 0000000..9148118 --- /dev/null +++ b/api-reference/operators/element-query/$exists.md @@ -0,0 +1,315 @@ +--- +title: $exists +description: The $exists operator retrieves documents that contain the specified field in their document structure. +type: operators +category: element-query +--- + +# $exists + +The $exists operator retrieves documents that contain the specified field. The $exists operator returns a value of true for documents that contain the specified field, even if the value of the field is null. The $exists operator returns a value of fall for documents that do not contain the specified field in their document structure. + +## Syntax + +```javascript +{ + : { $exists: } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to check for existence. | +| **`true or false`** | `true` for documents that contain the field (including null values), `false` for documents that do not contain the field. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find stores with promotion events + +To find any two stores with promotion events, run a query using the $exists operator on the promotionEvents array. Then, project only the ID and promotionEvents fields and limit the results to two documents from the result set. + +```javascript +db.stores.find({ + "promotionEvents": { + $exists: true + } +}, { + "_id": 1, + "promotionEvents": { + $slice: 1 + } +}).limit(2) +``` + +This query returns the following results: + +```json + [ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { + "lat": -74.0427, + "lon": 160.8154 + }, + "staff": { + "employeeCount": { + "fullTime": 9, + "partTime": 18 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "Stockings", + "totalSales": 25731 + } + ], + "revenue": 25731 + }, + "promotionEvents": [ + { + "eventName": "Mega Savings Extravaganza", + "promotionalDates": { + "startDate": { + "Year": 2023, + "Month": 6, + "Day": 29 + }, + "endDate": { + "Year": 2023, + "Month": 7, + "Day": 7 + } + }, + "discounts": [ + { + "categoryName": "Stockings", + "discountPercentage": 16 + }, + { + "categoryName": "Tree Ornaments", + "discountPercentage": 8 + } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Marvinfort", + "storeOpeningDate": "2024-10-01T18:24:02.586Z", + "lastUpdated": "2024-10-02T18:24:02.000Z" + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "name": "Lakeshore Retail | Home Decor Hub - Franciscoton", + "location": { + "lat": 61.3945, + "lon": -3.6196 + }, + "staff": { + "employeeCount": { + "fullTime": 7, + "partTime": 6 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "Lamps", + "totalSales": 19880 + }, + { + "categoryName": "Rugs", + "totalSales": 20055 + } + ], + "revenue": 39935 + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Markdown Mania", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 25 + }, + "endDate": { + "Year": 2024, + "Month": 4, + "Day": 1 + } + }, + "discounts": [ + { + "categoryName": "Vases", + "discountPercentage": 8 + }, + { + "categoryName": "Lamps", + "discountPercentage": 5 + } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Franciscoton", + "lastUpdated": "2024-12-02T12:01:46.000Z", + "storeOpeningDate": "2024-09-03T07:21:46.045Z" + } +] +``` + +### Example 2: Confirm the presence of a nested field + +To retrieve any two stores with full time employees, run a query using the $exists operator on the nested staff.employeeCount.fullTime field. Then, project only the name and ID fields and limit the results to two documents from the result set. + +```javascript +db.stores.find({ + "staff.employeeCount.fullTime": { + $exists: true + } +}, { + "_id": 1, + "staff.employeeCount": 1 +}).limit(2) +``` + +This query returns the following results: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "staff": { + "employeeCount": { + "fullTime": 9, + "partTime": 18 + } + } + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "staff": { + "employeeCount": { + "fullTime": 7, + "partTime": 6 + } + } + } +] +``` diff --git a/api-reference/operators/element-query/$type.md b/api-reference/operators/element-query/$type.md new file mode 100644 index 0000000..38bb675 --- /dev/null +++ b/api-reference/operators/element-query/$type.md @@ -0,0 +1,230 @@ +--- +title: $type +description: The $type operator retrieves documents if the chosen field is of the specified type. +type: operators +category: element-query +--- + +# $type + +The `$type` operator retrieves documents if a chosen field is of the specified type. The $type operator is useful in data validation and ensuring consistency across documents in a collection. + +## Syntax + +```javascript +{ + : { $type: | } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The field to check the type of. | +| **`BSON type number`** | A number corresponding to the BSON type (e.g., 1 for double, 2 for string). | +| **`string alias`** | A string alias for the BSON type (e.g., "double", "string", "object", "array"). | + +## Common BSON Types + +| Type | Number | Alias | Description | +| --- | --- | --- | --- | +| Double | 1 | "double" | 64-bit floating point | +| String | 2 | "string" | UTF-8 string | +| Object | 3 | "object" | Embedded document | +| Array | 4 | "array" | Array | +| ObjectId | 7 | "objectId" | ObjectId | +| Boolean | 8 | "bool" | Boolean | +| Date | 9 | "date" | Date | +| Null | 10 | "null" | Null value | +| 32-bit integer | 16 | "int" | 32-bit integer | +| Timestamp | 17 | "timestamp" | Timestamp | +| 64-bit integer | 18 | "long" | 64-bit integer | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find stores with string-type names + +To find any store whose name is of type string, run a query using the $type operator on the name field. Then, project only the ID and name fields and limit the results to one document from the result set. + +```javascript +db.stores.find({ + "name": { + $type: "string" + } +}, { + "_id": 1, + "name": 1 +}).limit(1) +``` + +This query returns the following result: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort" + } +] +``` + +### Example 2: Data validation using multiple type checks + +This query demonstrates how to validate that essential fields in the collection's document structure have the desired data types. + +```javascript +db.stores.find({ + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": { + $type: "string" + }, + "location": { + $type: "object" + }, + "staff.employeeCount.fullTime": { + $type: ["int", "long"] + }, + "promotionEvents": { + $type: "array" + } + }, { + "_id": 1, + "name": 1, + "location": 1, + "staff": 1 + } +) +``` + +This query returns the following result. + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "location": { + "lat": -48.9752, + "lon": -141.6816 + }, + "staff": { + "employeeCount": { + "fullTime": 12 + } + } + } +] +``` diff --git a/api-reference/operators/evaluation-query/$expr.md b/api-reference/operators/evaluation-query/$expr.md new file mode 100644 index 0000000..d1a4efe --- /dev/null +++ b/api-reference/operators/evaluation-query/$expr.md @@ -0,0 +1,251 @@ +--- +title: $expr +description: The $expr operator allows the use of aggregation expressions within the query language, enabling complex field comparisons and calculations. +type: operators +category: evaluation-query +--- + +# $expr + +The `$expr` operator allows the use of aggregation expressions within the query language, which enables us to compare fields from the same document, perform calculations, and use aggregation operators in find operations. The `$expr` operator is useful for complex field comparisons that can't be achieved with traditional query operators. + +## Syntax + +```javascript +{ + $expr: { } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any valid aggregation expression that evaluates to a boolean value. The expression includes field comparisons, arithmetic operations, conditional expressions, and other aggregation operators. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Compare full-time and part-time staff + +The example retrieves stores with the number of part-time employees greater than full-time employees. + +```javascript +db.stores.find({_id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + $expr: { + $gt: ["$staff.employeeCount.partTime", "$staff.employeeCount.fullTime"] + } +}) +``` + +The query compares two fields within the specified (`_id`) document and returns it only if the condition is met (full-time staff count exceeds part-time staff count). + +```json +{ + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "location": { + "lat": 70.1272, + "lon": 69.7296 + }, + "staff": { + "contractorCount": 5, + "employeeCount": { "fullTime": 19, "partTime": 20 } + }, + "sales": { + "totalSales": 151864, + "salesByCategory": [ + { + "categoryName": "Sound Bars", + "totalSales": 2120 + }, + { + "categoryName": "Home Theater Projectors", + "totalSales": 45004 + } + }, + "storeOpeningDate": ISODate("2024-09-23T13:45:01.480Z"), + "lastUpdated": ISODate("2025-06-11T11:06:57.922Z"), + "status": "active", + "category": "high-volume", + "priority": 1, + "reviewDate": ISODate("2025-06-11T11:10:50.276Z") + } +] +``` + +### Example 2: Conditional logic with store location + +The example demonstrates the conditional logic usage with `$expr` pulling stores in the southern hemisphere where the staff efficiency ratio (sales per employee) exceeds 2000. + +```javascript +db.stores.find({_id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + $expr: { + $and: [ + { $gte: ["$location.lat", 70.1272] }, + { + $gt: [ + { + $divide: [ + "$sales.totalSales", + { $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] } + ] + }, + 2000 + ] + } + ] + } +}).limit(1) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "location": { + "lat": 70.1272, + "lon": 69.7296 + }, + "staff": { + "totalStaff": { + "fullTime": 19, + "partTime": 20 + } + }, + "sales": { + "totalSales": 151864, + "salesByCategory": [ + { + "categoryName": "Sound Bars", + "totalSales": 2120 + }, + { + "categoryName": "Home Theater Projectors", + "totalSales": 45004 + } + ] + }, + "storeOpeningDate": ISODate("2024-09-23T13:45:01.480Z"), + "lastUpdated": ISODate("2025-06-11T11:06:57.922Z"), + "status": "active", + "category": "high-volume", + "priority": 1, + "reviewDate": ISODate("2025-06-11T11:10:50.276Z") + } +] +``` diff --git a/api-reference/operators/evaluation-query/$jsonschema.md b/api-reference/operators/evaluation-query/$jsonschema.md new file mode 100644 index 0000000..8b173c3 --- /dev/null +++ b/api-reference/operators/evaluation-query/$jsonschema.md @@ -0,0 +1,280 @@ +--- +title: $jsonSchema +description: The $jsonSchema operator validates documents against a JSON Schema definition for data validation and structure enforcement. Discover supported features and limitations. +type: operators +category: evaluation-query +--- + +# $jsonSchema + +The `$jsonSchema` operator is used to validate documents against a JSON Schema specification. It ensures that documents conform to a predefined structure, data types, and validation rules. + +## Syntax + +The syntax for the `$jsonSchema` operator is as follows: + +```javascript +db.createCollection("collectionName", { + validator: { + $jsonSchema: { + bsonType: "object", + required: ["field1", "field2"], + properties: { + field1: { + bsonType: "string", + description: "Description of field1 requirements" + }, + field2: { + bsonType: "int", + minimum: 0, + description: "Description of field2 requirements" + } + } + } + }, + validationLevel: "strict", // Optional: "strict" or "moderate" + validationAction: "error" // Optional: "error" or "warn" +}) +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`bsonType`** | Specifies the Binary JSON (BSON) types that the field must match. Accepts string aliases used by the $type operator. | +| **`properties`** | Object defining validation rules for specific fields. | +| **`minimum/maximum`** | Numeric constraints for number fields. | +| **`minLength/maxLength`** | String length constraints. | +| **`minItems/maxItems`** | Array length constraints. | +| **`pattern`** | Regular expression pattern for string validation. | +| **`items`** | Schema validation for array elements. | +| **`uniqueItems`** | Boolean indicating if array items must be unique. | + +## Supported Keywords + +DocumentDB supports the following JSON Schema keywords: + +| Keyword | Type | Description | Usage | +|---------|------|-------------|--------| +| `additionalItems` | arrays | Schema for extra array items | Extended array validation | +| `bsonType` | all types | MongoDB extension - accepts BSON type aliases | `"string"`, `"int"`, `"double"`, `"object"`, `"array"`, `"bool"`, `"date"` | +| `exclusiveMinimum` | numbers | Exclusive minimum boundary | Advanced numeric validation | +| `exclusiveMaximum` | numbers | Exclusive maximum boundary | Advanced numeric validation | +| `items` | arrays | Schema for array elements | Array element validation | +| `minimum` | numbers | Minimum value constraint | Numeric validation | +| `maximum` | numbers | Maximum value constraint | Numeric validation | +| `minItems` | arrays | Minimum array length | Array size validation | +| `maxItems` | arrays | Maximum array length | Array size validation | +| `multipleOf` | numbers | Value must be multiple of specified number | Mathematical constraints | +| `minLength` | strings | Minimum string length | String validation | +| `maxLength` | strings | Maximum string length | String validation | +| `pattern` | strings | Regular expression pattern matching | String format validation | +| `properties` | objects | Define validation rules for object fields | Schema definition for nested objects | +| `required` | objects | Array of required field names | Enforce mandatory fields | +| `type` | all types | Standard JSON Schema types | `"object"`, `"array"`, `"number"`, `"boolean"`, `"string"`, `"null"` | +| `uniqueItems` | arrays | Enforce unique array elements | Data integrity | + +### Unsupported Keywords + +These JSON Schema keywords are yet to be supported in DocumentDB: + +| Keyword | Type | Reason for Non-Support | Workaround | +|---------|------|----------------------|------------| +| `additionalProperties` | objects | Not implemented | Use explicit `properties` definitions | +| `allOf` | all types | Logical operator not supported | Use nested validation | +| `anyOf` | all types | Logical operator not supported | Use separate queries | +| `dependencies` | objects | Complex dependency validation not supported | Handle in application logic | +| `description` | N/A | Might not appear in error messages | Informational only | +| `enum` | all types | Enumeration validation not supported | Use `$in` operator instead | +| `maxProperties` | objects | Property count validation not supported | Handle in application logic | +| `minProperties` | objects | Property count validation not supported | Handle in application logic | +| `not` | all types | Negation operator not supported | Use positive validation rules | +| `oneOf` | all types | Logical operator not supported | Use application-level validation | +| `patternProperties` | objects | Pattern-based property validation not supported | Use explicit property names | +| `title` | N/A | Metadata field not processed | Use `description` instead | + +## Examples + +Let's explore practical examples using the `stores` dataset: + +```json +{ + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "location": { + "lat": 60.7954, + "lon": -142.0012 + }, + "staff": { + "totalStaff": { + "fullTime": 18, + "partTime": 17 + } + }, + "sales": { + "totalSales": 37701, + "salesByCategory": [ + { + "categoryName": "Mattress Toppers", + "totalSales": 37701 + } + ] + } +} +``` + +### Example 1: Basic Structure Validation + +This query retrieves all stores with names between 5 and 100 characters long, and that geographic coordinates fall within valid ranges: latitude between -90 and 90, and longitude between -180 and 180. + +```javascript +db.stores.find({ + $jsonSchema: { + bsonType: "object", + properties: { + _id: { + bsonType: "string" + }, + name: { + bsonType: "string", + minLength: 5, + maxLength: 100 + }, + location: { + bsonType: "object", + properties: { + lat: { + bsonType: "double", + minimum: -90, + maximum: 90 + }, + lon: { + bsonType: "double", + minimum: -180, + maximum: 180 + } + } + } + } + } +}).limit(1) + +``` + +### Example 2: Sales Validation with Array Items + +This query retrieves all store documents where the sales field is a valid object containing a non-negative totalSales value and a salesByCategory array with at least one item. + +```javascript +db.stores.find({ + $jsonSchema: { + bsonType: "object", + properties: { + sales: { + bsonType: "object", + properties: { + totalSales: { + bsonType: "int", + minimum: 0 + }, + salesByCategory: { + bsonType: "array", + minItems: 1, + items: { + bsonType: "object", + properties: { + categoryName: { + bsonType: "string", + minLength: 1 + }, + totalSales: { + bsonType: "int", + minimum: 0 + } + } + } + } + } + } + } + } +}).limit(1) + +``` + +This query should return this output: + +```javascript +[ + { + _id: 'new-store-001', + name: 'Adatum Corporation - Downtown Branch', + sales: { totalSales: 5000 }, + createdDate: ISODate('2025-06-11T11:11:32.262Z'), + status: 'new', + staff: { totalStaff: { fullTime: 0, partTime: 0 } }, + version: 1, + storeOpeningDate: ISODate('2025-06-11T11:11:32.262Z'), + storeFeatures: 213 + } +] +``` + +### Example 3: Combining with Query Operators + +This query retrieves all store documents where the staff field is a valid object that includes a totalStaff subobject with at least one full-time staff member (fullTime ≥ 1) and sales.totalSales greater than 10,000. + +```javascript +db.stores.find({ + $and: [ + { + $jsonSchema: { + properties: { + staff: { + bsonType: "object", + properties: { + totalStaff: { + bsonType: "object", + properties: { + fullTime: { + bsonType: "int", + minimum: 1 + } + } + } + } + } + } + } + }, + // Additional query constraints + { + "sales.totalSales": { $gt: 10000 } + } + ] +}).limit(1) +``` + +This query returns the following result: + +```javascript +[ + { + _id: 'future-electronics-001', + address: { city: 'New Tech City' }, + name: 'Boulder Innovations - Future Electronics Hub', + sales: { totalSales: 25000 }, + establishedDate: ISODate('2025-06-11T11:14:23.147Z'), + categories: [ 'electronics', 'gadgets', 'smart-home' ], + promotionEvents: [], + ratings: { average: 0, count: 0, reviews: [] }, + inventory: { + lastUpdated: ISODate('2025-06-11T11:14:23.147Z'), + totalItems: 0, + lowStockAlerts: [] + }, + storeOpeningDate: ISODate('2025-06-11T11:11:32.262Z'), + storeFeatures: 120 + } +] +``` diff --git a/api-reference/operators/evaluation-query/$mod.md b/api-reference/operators/evaluation-query/$mod.md new file mode 100644 index 0000000..e2c5d7e --- /dev/null +++ b/api-reference/operators/evaluation-query/$mod.md @@ -0,0 +1,274 @@ +--- +title: $mod +description: The $mod operator performs a modulo operation on the value of a field and selects documents with a specified result. +type: operators +category: evaluation-query +--- + +# $mod + +The `$mod` operator performs a modulo operation on the value of a field and selects documents with a specified result. This operator is useful for finding documents where a numeric field value, when divided by a divisor, leaves a specific remainder. It commonly serves for pagination, sampling data, or finding patterns in numeric sequences. + +## Syntax + +```javascript +{ + : { $mod: [ , ] } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The field to perform the modulo operation on. The field must contain numeric values. | +| **``** | The number to divide the field value by. Must be a positive number. | +| **``** | The expected remainder after the modulo operation. Must be a non-negative number less than the divisor. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find stores with sales divisible by 1000 + +This query retrieves stores where the total sales are divisible by 1000 (useful for identifying round sales figures). + +```javascript +db.stores.find({ + "sales.totalSales": { $mod: [1000, 0] } +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "new-store-001", + "name": "TechWorld Electronics - Downtown Branch", + "sales": { + "totalSales": 5000 + }, + "createdDate": "2025-06-11T11:11:32.262Z", + "status": "new", + "staff": { + "totalStaff": { + "fullTime": 0, + "partTime": 0 + } + }, + "version": 1 + }, + { + "_id": "gaming-store-mall-001", + "name": "Gaming Paradise - Mall Location", + "location": { + "lat": 35.6762, + "lon": 139.6503 + }, + "createdDate": "2025-06-11T11:13:27.180Z", + "status": "active", + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 12 + }, + "manager": "Alex Johnson", + "departments": [ + "gaming", + "accessories", + "repairs" + ] + }, + "sales": { + "totalSales": 0, + "salesByCategory": [] + }, + "operatingHours": { + "weekdays": "10:00-22:00", + "weekends": "09:00-23:00" + }, + "metadata": { + "version": 1, + "source": "store-management-system" + } + } +] +``` + +### Example 2: Pagination-style querying + +This query retrieves stores where the part-time employee count leaves a remainder of 0 when divided by 4 (useful for creating data subsets). + +```javascript +db.stores.find({ + "staff.totalStaff.partTime": { $mod: [4, 0] } +}) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "new-store-001", + "name": "TechWorld Electronics - Downtown Branch", + "sales": { + "totalSales": 5000 + }, + "createdDate": "2025-06-11T11:11:32.262Z", + "status": "new", + "staff": { + "totalStaff": { + "fullTime": 0, + "partTime": 0 + } + }, + "version": 1 + }, + { + "_id": "gaming-store-mall-001", + "name": "Gaming Paradise - Mall Location", + "location": { + "lat": 35.6762, + "lon": 139.6503 + }, + "createdDate": "2025-06-11T11:13:27.180Z", + "status": "active", + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 12 + }, + "manager": "Alex Johnson", + "departments": [ + "gaming", + "accessories", + "repairs" + ] + }, + "sales": { + "totalSales": 0, + "salesByCategory": [] + }, + "operatingHours": { + "weekdays": "10:00-22:00", + "weekends": "09:00-23:00" + }, + "metadata": { + "version": 1, + "source": "store-management-system" + } + } +] +``` diff --git a/api-reference/operators/evaluation-query/$regex.md b/api-reference/operators/evaluation-query/$regex.md new file mode 100644 index 0000000..7589322 --- /dev/null +++ b/api-reference/operators/evaluation-query/$regex.md @@ -0,0 +1,328 @@ +--- +title: $regex +description: The $regex operator provides regular expression capabilities for pattern matching in queries, allowing flexible string matching and searching. +type: operators +category: evaluation-query +--- + +# $regex + +The `$regex` operator provides regular expression capabilities for pattern matching in queries. It allows you to search for documents where a field matches a specified regular expression pattern. This operator is useful for flexible string searching, pattern validation, and complex text filtering operations. + +## Syntax + +The syntax for the `$regex` operator is as follows: + +```javascript +{ + : { $regex: , $options: } +} +``` + +Or the shorter form: + +```javascript +{ + : { $regex: // } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The field to search in. Must contain string values. | +| **``** | The regular expression pattern to match against. | +| **``** | Optional. Regular expression options such as case-insensitive matching. Common options include 'i' (case insensitive), 'm' (multiline), 's' (dot all), and 'x' (extended). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "name": "First Up Consultants | Bed and Bath Pantry - Port Antone", + "location": { + "lat": 87.2239, + "lon": -129.0506 + }, + "staff": { + "employeeCount": { + "fullTime": 8, + "partTime": 7 + } + }, + "sales": { + "salesByCategory": [ + { "categoryName": "Towel Sets", "totalSales": 520 }, + { "categoryName": "Bath Accessories", "totalSales": 41710 }, + { "categoryName": "Drapes", "totalSales": 42893 }, + { "categoryName": "Towel Racks", "totalSales": 30773 }, + { "categoryName": "Hybrid Mattresses", "totalSales": 39491 }, + { "categoryName": "Innerspring Mattresses", "totalSales": 6410 }, + { "categoryName": "Bed Frames", "totalSales": 41917 }, + { "categoryName": "Mattress Protectors", "totalSales": 44124 }, + { "categoryName": "Bath Towels", "totalSales": 5671 }, + { "categoryName": "Turkish Towels", "totalSales": 25674 } + ], + "revenue": 279183 + }, + "promotionEvents": [ + { + "eventName": "Discount Derby", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 5 } + }, + "discounts": [ + { "categoryName": "Microfiber Towels", "discountPercentage": 6 }, + { "categoryName": "Bath Sheets", "discountPercentage": 16 }, + { "categoryName": "Towels", "discountPercentage": 10 }, + { "categoryName": "Hand Towels", "discountPercentage": 11 }, + { "categoryName": "Kitchen Towels", "discountPercentage": 21 }, + { "categoryName": "Placemat", "discountPercentage": 11 }, + { "categoryName": "Bath Accessories", "discountPercentage": 11 }, + { "categoryName": "Bedspreads", "discountPercentage": 21 }, + { "categoryName": "Shower Curtains", "discountPercentage": 24 }, + { "categoryName": "Pillow Top Mattresses", "discountPercentage": 10 } + ] + }, + { + "eventName": "Big Bargain Blitz", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 3 } + }, + "discounts": [ + { "categoryName": "Mattress Toppers", "discountPercentage": 24 }, + { "categoryName": "Pillow Cases", "discountPercentage": 14 }, + { "categoryName": "Soap Dispensers", "discountPercentage": 20 }, + { "categoryName": "Beach Towels", "discountPercentage": 18 }, + { "categoryName": "Bath Mats", "discountPercentage": 22 }, + { "categoryName": "Blankets", "discountPercentage": 12 }, + { "categoryName": "Kitchen Towels", "discountPercentage": 8 }, + { "categoryName": "Memory Foam Mattresses", "discountPercentage": 14 }, + { "categoryName": "Placemat", "discountPercentage": 17 }, + { "categoryName": "Bed Frames", "discountPercentage": 23 } + ] + }, + { + "eventName": "Massive Markdown Mania", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Bed Skirts", "discountPercentage": 17 }, + { "categoryName": "Shower Curtains", "discountPercentage": 23 }, + { "categoryName": "Bath Towels", "discountPercentage": 21 }, + { "categoryName": "Memory Foam Mattresses", "discountPercentage": 11 }, + { "categoryName": "Bathrobes", "discountPercentage": 19 }, + { "categoryName": "Bath Accessories", "discountPercentage": 5 }, + { "categoryName": "Box Springs", "discountPercentage": 21 }, + { "categoryName": "Hand Towels", "discountPercentage": 13 }, + { "categoryName": "Tablecloths", "discountPercentage": 19 }, + { "categoryName": "Duvet Covers", "discountPercentage": 23 } + ] + }, + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Adjustable Beds", "discountPercentage": 19 }, + { "categoryName": "Mattress Toppers", "discountPercentage": 23 }, + { "categoryName": "Washcloths", "discountPercentage": 7 }, + { "categoryName": "Comforters", "discountPercentage": 24 }, + { "categoryName": "Kitchen Towels", "discountPercentage": 7 }, + { "categoryName": "Pillows", "discountPercentage": 13 }, + { "categoryName": "Bath Sheets", "discountPercentage": 25 }, + { "categoryName": "Napkins", "discountPercentage": 25 }, + { "categoryName": "Bath Towels", "discountPercentage": 15 }, + { "categoryName": "Beach Towels", "discountPercentage": 15 } + ] + } + ], + "company": "First Up Consultants", + "city": "Port Antone", + "storeOpeningDate": { "$date": "2024-09-19T17:31:59.665Z" }, + "lastUpdated": { "$timestamp": { "t": 1729359119, "i": 1 } } +} +``` + +### Example 1: Find stores by name pattern + +This query retrieves all the stores containing "Consultants" in their name (case-insensitive). + +```javascript +db.stores.find( + { name: { $regex: "Consultants", $options: "i" } }, + { _id: 1, name: 1, storeOpeningDate: 1 } +).limit(3) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "name": "First Up Consultants | Bed and Bath Pantry - Port Antone", + "storeOpeningDate": "2024-09-19T17:31:59.665Z" + }, + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "storeOpeningDate": "2024-09-10T13:43:51.209Z" + }, + { + "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad", + "name": "First Up Consultants | Plumbing Supply Shoppe - New Ubaldofort", + "storeOpeningDate": "2024-09-19T08:27:44.268Z" + } +] +``` + +### Example 2: Advanced pattern matching for category names + +This query retrieves stores selling products with a category name that starts with a vowel. + +```javascript +db.stores.find( + { + "sales.salesByCategory.categoryName": { $regex: "^[AEIOUaeiou]" } + }, + { _id: 1, name: 1, "sales.salesByCategory.categoryName": 1 } +).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a", + "name": "Relecloud | Toy Collection - North Jaylan", + "sales": { + "salesByCategory": [ + { "categoryName": "Educational Toys" } + ] + } + }, + { + "_id": "4e064f0a-7e30-4701-9a80-eff3caf46ce8", + "name": "Fourth Coffee | Outdoor Furniture Deals - Lucianohaven", + "sales": { + "salesByCategory": [ + { "categoryName": "Outdoor Swings" }, + { "categoryName": "Hammocks" } + ] + } + } +] +``` + +### Example 3: Find stores with specific naming conventions + +This query retrieves stores with names containing a pipe character (|) separator. + +```javascript +db.stores.find( +{ name: { $regex: "\\|" }}, +{ _id: 1, name: 1, "sales.salesByCategory.categoryName": 1}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "sales": { + "salesByCategory": [ + { "categoryName": "Desk Lamps" } + ] + } + }, + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "sales": { + "salesByCategory": [ + { "categoryName": "Stockings" } + ] + } + } +] +``` + +### Example 4: Complex pattern for discount categories + +This query retrieves stores with categories containing both "Bath" and ending with "s". + +```javascript +db.stores.aggregate([ + { $match: { "promotionEvents.discounts.categoryName": { $regex: "Bath.*s$", $options: "i" } } }, + { $project: { "_id": 1, "name": 1, "promotionEvents.discounts.categoryName":1 }}, + { $match: {"promotionEvents.discounts.categoryName": { $ne: [] }} }, + { $limit: 2 }]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "name": "First Up Consultants | Bed and Bath Pantry - Port Antone", + "promotionEvents": [ + { + "discounts": [ + { "categoryName": "Bath Sheets", "discountPercentage": 16 }, + { "categoryName": "Bath Accessories", "discountPercentage": 11 } + ] + }, + { + "discounts": [ + { "categoryName": "Bath Mats", "discountPercentage": 22 } + ] + }, + { + "discounts": [ + { "categoryName": "Bath Towels", "discountPercentage": 21 }, + { "categoryName": "Bathrobes", "discountPercentage": 19 }, + { "categoryName": "Bath Accessories", "discountPercentage": 5 } + ] + }, + { + "discounts": [ + { "categoryName": "Bath Sheets", "discountPercentage": 25 }, + { "categoryName": "Bath Towels", "discountPercentage": 15 } + ] + } + ] + }, + { + "_id": "27ef6004-70fa-4217-8395-0eabc4cc9841", + "name": "Fabrikam, Inc. | Bed and Bath Store - O'Connerborough", + "promotionEvents": [ + { + "discounts": [ + { "categoryName": "Bath Accessories", "discountPercentage": 24 } + ] + }, + { + "discounts": [ + { "categoryName": "Bathrobes", "discountPercentage": 18 }, + { "categoryName": "Bath Towels", "discountPercentage": 14 }, + { "categoryName": "Bath Accessories", "discountPercentage": 20 } + ] + } + ] + } +] +``` diff --git a/api-reference/operators/evaluation-query/$text.md b/api-reference/operators/evaluation-query/$text.md new file mode 100644 index 0000000..7319fa1 --- /dev/null +++ b/api-reference/operators/evaluation-query/$text.md @@ -0,0 +1,533 @@ +--- +title: $text +description: The $text operator performs text search on the content of indexed string fields, enabling full-text search capabilities. +type: operators +category: evaluation-query +--- + +# $text + +The `$text` operator performs text search on the content of indexed string fields. It enables full-text search capabilities by searching for specified words or phrases across text-indexed fields. The `$text` operator requires at least one text index on the collection and provides features like stemming, stop word removal, and relevance scoring. + +## Syntax + +```javascript +{ + $text: { + $search: , + $language: , + $caseSensitive: , + $diacriticSensitive: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`$search`** | Required. The search string containing the terms to search for. Multiple terms are treated as an OR operation unless enclosed in quotes for phrase matching. | +| **`$language`** | Optional. Language for the text search, which determines the stemming rules and stop words, though the system uses the index's default language if you don't specify one | +| **`$caseSensitive`** | Optional. Boolean flag to enable case-sensitive search. Default is false (case-insensitive). | +| **`$diacriticSensitive`** | Optional. Boolean flag to enable diacritic-sensitive search. Default is false (diacritic-insensitive). | + +## Prerequisite + +Before using the `$text` operator, you must create a text index on the fields you want to search. + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "name": "First Up Consultants | Bed and Bath Pantry - Port Antone", + "location": { + "lat": 87.2239, + "lon": -129.0506 + }, + "staff": { + "employeeCount": { + "fullTime": 8, + "partTime": 7 + } + }, + "sales": { + "salesByCategory": [ + { "categoryName": "Towel Sets", "totalSales": 520 }, + { "categoryName": "Bath Accessories", "totalSales": 41710 }, + { "categoryName": "Drapes", "totalSales": 42893 }, + { "categoryName": "Towel Racks", "totalSales": 30773 }, + { "categoryName": "Hybrid Mattresses", "totalSales": 39491 }, + { "categoryName": "Innerspring Mattresses", "totalSales": 6410 }, + { "categoryName": "Bed Frames", "totalSales": 41917 }, + { "categoryName": "Mattress Protectors", "totalSales": 44124 }, + { "categoryName": "Bath Towels", "totalSales": 5671 }, + { "categoryName": "Turkish Towels", "totalSales": 25674 } + ], + "revenue": 279183 + }, + "promotionEvents": [ + { + "eventName": "Discount Derby", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 5 } + }, + "discounts": [ + { "categoryName": "Microfiber Towels", "discountPercentage": 6 }, + { "categoryName": "Bath Sheets", "discountPercentage": 16 }, + { "categoryName": "Towels", "discountPercentage": 10 }, + { "categoryName": "Hand Towels", "discountPercentage": 11 }, + { "categoryName": "Kitchen Towels", "discountPercentage": 21 }, + { "categoryName": "Placemat", "discountPercentage": 11 }, + { "categoryName": "Bath Accessories", "discountPercentage": 11 }, + { "categoryName": "Bedspreads", "discountPercentage": 21 }, + { "categoryName": "Shower Curtains", "discountPercentage": 24 }, + { "categoryName": "Pillow Top Mattresses", "discountPercentage": 10 } + ] + }, + { + "eventName": "Big Bargain Blitz", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 3 } + }, + "discounts": [ + { "categoryName": "Mattress Toppers", "discountPercentage": 24 }, + { "categoryName": "Pillow Cases", "discountPercentage": 14 }, + { "categoryName": "Soap Dispensers", "discountPercentage": 20 }, + { "categoryName": "Beach Towels", "discountPercentage": 18 }, + { "categoryName": "Bath Mats", "discountPercentage": 22 }, + { "categoryName": "Blankets", "discountPercentage": 12 }, + { "categoryName": "Kitchen Towels", "discountPercentage": 8 }, + { "categoryName": "Memory Foam Mattresses", "discountPercentage": 14 }, + { "categoryName": "Placemat", "discountPercentage": 17 }, + { "categoryName": "Bed Frames", "discountPercentage": 23 } + ] + }, + { + "eventName": "Massive Markdown Mania", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Bed Skirts", "discountPercentage": 17 }, + { "categoryName": "Shower Curtains", "discountPercentage": 23 }, + { "categoryName": "Bath Towels", "discountPercentage": 21 }, + { "categoryName": "Memory Foam Mattresses", "discountPercentage": 11 }, + { "categoryName": "Bathrobes", "discountPercentage": 19 }, + { "categoryName": "Bath Accessories", "discountPercentage": 5 }, + { "categoryName": "Box Springs", "discountPercentage": 21 }, + { "categoryName": "Hand Towels", "discountPercentage": 13 }, + { "categoryName": "Tablecloths", "discountPercentage": 19 }, + { "categoryName": "Duvet Covers", "discountPercentage": 23 } + ] + }, + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Adjustable Beds", "discountPercentage": 19 }, + { "categoryName": "Mattress Toppers", "discountPercentage": 23 }, + { "categoryName": "Washcloths", "discountPercentage": 7 }, + { "categoryName": "Comforters", "discountPercentage": 24 }, + { "categoryName": "Kitchen Towels", "discountPercentage": 7 }, + { "categoryName": "Pillows", "discountPercentage": 13 }, + { "categoryName": "Bath Sheets", "discountPercentage": 25 }, + { "categoryName": "Napkins", "discountPercentage": 25 }, + { "categoryName": "Bath Towels", "discountPercentage": 15 }, + { "categoryName": "Beach Towels", "discountPercentage": 15 } + ] + } + ], + "company": "First Up Consultants", + "city": "Port Antone", + "storeOpeningDate": { "$date": "2024-09-19T17:31:59.665Z" }, + "lastUpdated": { "$timestamp": { "t": 1729359119, "i": 1 } } +} +``` + +### Example 1: Simple text search + +This query retrieves stores containing the word "Microphone" in indexed text fields. + +```javascript +// First create a text index +db.stores.createIndex({ "name": "text", "sales.salesByCategory.categoryName": "text" }) + +// Then perform the search +db.stores.find( +{ $text: { $search: "Microphone" }}, +{ _id: 1, name: 1, "sales.salesByCategory.categoryName": 1 }).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "sales": { + "salesByCategory": [ + { "categoryName": "Lavalier Microphones" }, + { "categoryName": "Wireless Microphones" } + ] + } + }, + { + "_id": "7cecdb2d-33c2-434c-ad55-bf529f68044b", + "name": "Contoso, Ltd. | Microphone Haven - O'Connellside", + "sales": { + "salesByCategory": [ + { "categoryName": "Microphone Accessories" }, + { "categoryName": "Wireless Microphones" } + ] + } + } +] +``` + +### Example 2: Multiple term search + +The query retrieves stores related to "Home Decor" (multiple terms treated as `OR` by default). + +```javascript +// First create a text index +db.stores.createIndex({ "name": "text", "sales.salesByCategory.categoryName": "text" }) + +// Then perform the search +db.stores.find( +{ $text: { $search: "Home Decor" }}, +{ _id: 1, name: 1, "sales.salesByCategory.categoryName": 1 }).limit(5) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "sales": { + "salesByCategory": [ + { "categoryName": "Desk Lamps" } + ] + } + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "name": "Lakeshore Retail | Home Decor Hub - Franciscoton", + "sales": { + "salesByCategory": [ + { "categoryName": "Lamps" }, + { "categoryName": "Rugs" } + ] + } + }, + { + "_id": "1a2c387b-bb43-4b14-a6cd-cc05a5dbfbd5", + "name": "Contoso, Ltd. | Smart Home Device Vault - Port Katarina", + "sales": { + "salesByCategory": [ + { "categoryName": "Smart Locks" }, + { "categoryName": "Smart Home Hubs" } + ] + } + }, + { + "_id": "15e9ca57-ebc1-4191-81c2-5dc2f4ebd973", + "name": "Trey Research | Gardening Supply Stop - Port Saul", + "sales": { + "salesByCategory": [ + { "categoryName": "Garden Decor" }, + { "categoryName": "Pruning Shears" } + ] + } + }, + { + "_id": "dda2a7d2-6984-40cc-bbea-4cbfbc06d8a3", + "name": "Contoso, Ltd. | Home Improvement Closet - Jaskolskiview", + "sales": { + "salesByCategory": [ + { "categoryName": "Lumber" }, + { "categoryName": "Windows" } + ] + } + } +] +``` + +### Example 3: Phrase search + +This query searches for the exact phrase "Home Theater" using quotes. + +```javascript +db.stores.find( + { $text: { $search: "\"Home Theater\"" }}, + { _id: 1, name: 1, "sales.salesByCategory.categoryName": 1 }).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "0bc4f653-e64e-4342-ae7f-9611dfd37800", + "name": "Tailwind Traders | Speaker Bazaar - North Mireyamouth", + "sales": { + "salesByCategory": [ + { "categoryName": "Home Theater Speakers" } + ] + } + }, + { + "_id": "28bb05ed-d516-4186-9144-b9eeee30917a", + "name": "Adatum Corporation | Home Entertainment Market - East Bennettville", + "sales": { + "salesByCategory": [ + { "categoryName": "Media Players" }, + { "categoryName": "Home Theater Projectors" }, + { "categoryName": "Projector Accessories" }, + { "categoryName": "Sound Bars" }, + { "categoryName": "Blu-ray Players" } + ] + } + } +] +``` + +### Example 4: Exclude terms with negation + +This query searches for stores with "Audio" but exclude the ones with "Wireless". + +```javascript +db.stores.find( + { $text: { $search: "Audio -Wireless" }}, + { _id: 1, name: 1, "sales.salesByCategory.categoryName": 1 }).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "32afe6ec-dd3c-46b3-a681-ed041b032c39", + "name": "Relecloud | Audio Equipment Gallery - Margretshire", + "sales": { + "salesByCategory": [ + { "categoryName": "Audio Receivers" }, + { "categoryName": "Portable Bluetooth Speakers" } + ] + } + }, + { + "_id": "a3d3e59f-54bd-44be-943c-50dca5c4d667", + "name": "Contoso, Ltd. | Audio Equipment Shop - West Darrion", + "sales": { + "salesByCategory": [ + { "categoryName": "Soundbars" } + ] + } + } +] +``` + +### Example 5: Case-sensitive search + +> [!NOTE] +> Support for case-sensitive is in pipeline and should be released soon. + +The example allows performing a case-sensitive search for "BAZAAR". + +```javascript +db.stores.find( + { $text: { $search: "BAZAAR", $caseSensitive: true } }, + { _id: 1, name: 1, "sales.salesByCategory.categoryName": 1 } +).limit(2) +``` + +The query will match documents where "BAZAAR" appears in exactly that case. + +```json +[ + { + "_id": "future-electronics-001", + "name": "Future Electronics Hub", + "sales": { "totalSales": 25000 } + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "sales": { + "salesByCategory": [ + { "categoryName": "Sound Bars" }, + { "categoryName": "Game Controllers" }, + { "categoryName": "Remote Controls" }, + { "categoryName": "VR Games" } + ], + "totalSales": 160000 + } + } +] +``` + +### Example 6: Get text search scores + +This query retrieves text search results with relevance scores for ranking. + +```javascript +db.stores.find( + { $text: { $search: "Hub" } }, + { score: { $meta: "textScore" } } +).sort({ score: { $meta: "textScore" } }).limit(5) +``` + +The first five results returned by this query are: + +```json +[ + { "_id": "511c9932-d647-48dd-9bd8-baf47b593f88", "score": 2 }, + { "_id": "a0a2f05c-6085-4c99-9781-689af759662f", "score": 2 }, + { "_id": "fb5aa470-557c-43cb-8ca0-5915d6cae34b", "score": 2 }, + { "_id": "1a2c387b-bb43-4b14-a6cd-cc05a5dbfbd5", "score": 1 }, + { "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", "score": 1 } +] +``` + +### Example 7: Search across multiple categories + +First, create a comprehensive text index to search across all text fields. + +```javascript +// Create comprehensive text index +db.stores.createIndex({ + name: "text", + "sales.salesByCategory.categoryName": "text", + "promotionEvents.eventName": "text", + "promotionEvents.discounts.categoryName": "text" +}) + +// Search across all indexed fields +db.stores.find( +{ $text: { $search: "\"Home Theater\"" }}, +{ name: 1, "sales.salesByCategory.categoryName": 1, "promotionEvents.eventName": 1, "promotionEvents.discounts.categoryName": 1}).limit(2) +``` + +The first two results returned by this query. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "sales": { + "salesByCategory": [ + { "categoryName": "Sound Bars" }, + { "categoryName": "Game Controllers" }, + { "categoryName": "Remote Controls" }, + { "categoryName": "VR Games" } + ] + }, + "promotionEvents": [ + { + "eventName": "Massive Markdown Mania", + "discounts": [ + { "categoryName": "DVD Players" }, + { "categoryName": "Projector Lamps" }, + { "categoryName": "Media Players" }, + { "categoryName": "Blu-ray Players" }, + { "categoryName": "Home Theater Systems" }, + { "categoryName": "Televisions" } + ] + }, + { + "eventName": "Fantastic Deal Days", + "discounts": [ + { "categoryName": "TV Mounts" }, + { "categoryName": "Game Accessories" }, + { "categoryName": "Portable Projectors" }, + { "categoryName": "Projector Screens" }, + { "categoryName": "Blu-ray Players" }, + { "categoryName": "DVD Players" } + ] + }, + { + "eventName": "Discount Delight Days", + "discounts": [ + { "categoryName": "Game Controllers" }, + { "categoryName": "Home Theater Projectors" }, + { "categoryName": "Sound Bars" }, + { "categoryName": "Media Players" }, + { "categoryName": "Televisions" }, + { "categoryName": "Projector Lamps" } + ] + }, + { + "eventName": "Super Sale Spectacular", + "discounts": [ + { "categoryName": "Laser Projectors" }, + { "categoryName": "Projector Screens" }, + { "categoryName": "PC Games" }, + { "categoryName": "PlayStation Games" }, + { "categoryName": "TV Mounts" }, + { "categoryName": "Mobile Games" } + ] + }, + { + "eventName": "Grand Deal Days", + "discounts": [ + { "categoryName": "Remote Controls" }, + { "categoryName": "Televisions" }, + { "categoryName": "Business Projectors" }, + { "categoryName": "Laser Projectors" }, + { "categoryName": "Projectors" }, + { "categoryName": "Projector Screens" } + ] + }, + { + "eventName": "Major Bargain Bash", + "discounts": [ + { "categoryName": "Sound Bars" }, + { "categoryName": "VR Games" }, + { "categoryName": "Xbox Games" }, + { "categoryName": "Projector Accessories" }, + { "categoryName": "Mobile Games" }, + { "categoryName": "Projector Cases" } + ] + } + ] + }, + { + "_id": "0bc4f653-e64e-4342-ae7f-9611dfd37800", + "name": "Tailwind Traders | Speaker Bazaar - North Mireyamouth", + "sales": { + "salesByCategory": [ + { "categoryName": "Home Theater Speakers" } + ] + }, + "promotionEvents": [ + { + "eventName": "Epic Bargain Bash", + "discounts": [ + { "categoryName": "Bluetooth Speakers" }, + { "categoryName": "Outdoor Speakers" } + ] + }, + { + "eventName": "Fantastic Deal Days", + "discounts": [ + { "categoryName": "Portable Speakers" }, + { "categoryName": "Home Theater Speakers" } + ] + } + ] + } +] +``` diff --git a/api-reference/operators/field-update/$currentdate.md b/api-reference/operators/field-update/$currentdate.md new file mode 100644 index 0000000..504d088 --- /dev/null +++ b/api-reference/operators/field-update/$currentdate.md @@ -0,0 +1,200 @@ +--- +title: $currentDate +description: The $currentDate operator sets the value of a field to the current date, either as a Date or a timestamp. +type: operators +category: field-update +--- + +# $currentDate + +The `$currentDate` operator sets the value of a field to the current date, either as a Date or a timestamp. This operator is useful for tracking when documents were last modified or for setting creation timestamps. + +## Syntax + +```javascript +{ + $currentDate: { + : , + : , + ... + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The name of the field to set to the current date. | +| **`typeSpecification`** | Optional. Specifies the type of the date value. Can be `true` (for Date type) or `{ $type: "timestamp" }` for timestamp type. Default is `true` (Date). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "location": { + "lat": 60.1441, + "lon": -141.5012 + }, + "staff": { + "totalStaff": { + "fullTime": 2, + "partTime": 0 + } + }, + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ], + "company": "Lakeshore Retail", + "city": "Port Cecile", + "lastUpdated": { + "$date": "2024-12-11T10:21:58.274Z" + } +} +``` + +### Example 1: Setting current date + +To add a `lastUpdated` field with the current date to a store document, use the $currentDate operator to create the field with the current date as a Date object. + +```javascript +db.stores.updateOne( + { "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" }, + { + $currentDate: { + "lastUpdated": true + } + } +) +``` + +This operation returns the following the result. + +```json +{ + acknowledged: true, + insertedId: null, + matchedCount: 1, + modifiedCount: 1, + upsertedCount: 0 +} + +``` + +### Example 2: Setting current timestamp + +To add both a date field and a timestamp field to track modifications, use the $currentDate operator with a value of true and with a typestamp value. + +```javascript +db.stores.updateOne( + { "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" }, + { + $currentDate: { + "lastModified": true, + "lastModifiedTimestamp": { $type: "timestamp" } + } + } +) +``` + +This operation returns the following result + +```json +{ + acknowledged: true, + insertedId: null, + matchedCount: Long("1"), + modifiedCount: Long("1"), + upsertedCount: 0 +} +``` + +### Example 3: Updating nested fields + +Set current date for nested fields in the document structure. + +```javascript +db.stores.updateOne( + { "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" }, + { + $currentDate: { + "sales.lastSalesUpdate": true, + "staff.lastStaffUpdate": { $type: "timestamp" } + } + } +) +``` + +This operation returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "lastUpdated": ISODate("2025-02-12T10:30:45.123Z"), + "lastModified": ISODate("2025-02-12T10:30:45.123Z"), + "lastModifiedTimestamp": Timestamp(1739450445, 1), + "sales": { + "totalSales": 37701, + "lastSalesUpdate": ISODate("2025-02-12T10:30:45.123Z"), + "salesByCategory": [ + { + "categoryName": "Mattress Toppers", + "totalSales": 37701 + } + ] + }, + "staff": { + "totalStaff": { + "fullTime": 18, + "partTime": 17 + }, + "lastStaffUpdate": Timestamp(1739450445, 1) + } + } +] +``` diff --git a/api-reference/operators/field-update/$inc.md b/api-reference/operators/field-update/$inc.md new file mode 100644 index 0000000..d5ed5ff --- /dev/null +++ b/api-reference/operators/field-update/$inc.md @@ -0,0 +1,156 @@ +--- +title: $inc +description: The $inc operator increments the value of a field by a specified amount. +type: operators +category: field-update +--- + +# $inc + +The `$inc` operator increments the value of a field by a specified amount. If the field doesn't exist, `$inc` creates the field and sets it to the specified value. The operator accepts positive and negative values for incrementing and decrementing respectively. + +## Syntax + +The syntax for the `$inc` operator is as follows: + +```javascript +{ + $inc: { + : , + : , + ... + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The name of the field to increment. | +| **`amount`** | The increment value. Must be a number (positive for increment, negative for decrement). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "staff": { + "totalStaff": { + "fullTime": 19, + "partTime": 20 + } + }, + "sales": { + "totalSales": 151864, + "salesByCategory": [ + { + "categoryName": "Sound Bars", + "totalSales": 2120 + }, + { + "categoryName": "Home Theater Projectors", + "totalSales": 45004 + } + ] + } +} +``` + +### Example 1: Incrementing staff count + +To increase the full-time staff count by 3, use the $inc operator on the fullTime staff field with a value of 3. + +```javascript +db.stores.updateOne( + { "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" }, + { + $inc: { + "staff.totalStaff.fullTime": 3 + } + } +) +``` + +### Example 2: Decreasing and increasing values + +To decrease the part-time staff by 2 and increase total sales by 5000, use the $inc operator on both fields with values of -2 and 5000 respectively. + +```javascript +db.stores.updateOne( + { "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" }, + { + $inc: { + "staff.totalStaff.partTime": -2, + "sales.totalSales": 5000 + } + } +) +``` + +### Example 3: Creating New Fields + +If a field doesn't exist, `$inc` creates it with the specified value. + +```javascript +db.stores.updateOne( + { "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" }, + { + $inc: { + "staff.contractorCount": 5, + "sales.monthlyTarget": 200000 + } + } +) +``` + +### Example 4: Incrementing array element values + +Update specific sales figures within the salesByCategory array using positional operators. + +```javascript +db.stores.updateOne( + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "sales.salesByCategory.categoryName": "Sound Bars" + }, + { + $inc: { + "sales.salesByCategory.$.totalSales": 500 + } + } +) +``` + +After these operations, the document is updated as follows: + +```json +{ + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "staff": { + "totalStaff": { + "fullTime": 22, + "partTime": 18 + }, + "contractorCount": 5 + }, + "sales": { + "totalSales": 156864, + "monthlyTarget": 200000, + "salesByCategory": [ + { + "categoryName": "Sound Bars", + "totalSales": 2620 + }, + { + "categoryName": "Home Theater Projectors", + "totalSales": 45004 + } + ] + } +} +``` diff --git a/api-reference/operators/field-update/$mul.md b/api-reference/operators/field-update/$mul.md new file mode 100644 index 0000000..fea8e68 --- /dev/null +++ b/api-reference/operators/field-update/$mul.md @@ -0,0 +1,294 @@ +--- +title: $mul +description: The $mul operator multiplies the value of a field by a specified number. +type: operators +category: field-update +--- + +# $mul + +The `$mul` operator multiplies the value of a field by a specified number. If the field does not exist, `$mul` creates the field and sets it to zero. This operator is useful for applying percentage changes, scaling values, or performing bulk calculations on numeric fields. + +## Syntax + +```javascript +{ + $mul: { + : , + : , + ... + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The name of the field to multiply. | +| **`number`** | The number to multiply the field value by. Must be a numeric value. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Applying percentage increase + +Apply a 10% increase to total sales (multiply by 1.1). This will change `totalSales` from 24863 to 27349.3 (24863 × 1.1). + +```javascript +db.stores.updateOne( + { "_id": "438db151-04b8-4422-aa97-acf94bc69cfc" }, + { + $mul: { + "sales.totalSales": 1.1 + } + } +) +``` + +### Example 2: Applying discount + +Apply a 20% discount to sales figures (multiply by 0.8). + +```javascript +db.stores.updateOne( + { "_id": "438db151-04b8-4422-aa97-acf94bc69cfc" }, + { + $mul: { + "sales.totalSales": 0.8 + } + } +) +``` + +### Example 3: Multiple field operations + +Apply different multipliers to multiple fields simultaneously. + +```javascript +db.stores.updateOne( + { "_id": "438db151-04b8-4422-aa97-acf94bc69cfc" }, + { + $mul: { + "staff.totalStaff.fullTime": 1.5, + "staff.totalStaff.partTime": 2, + "sales.totalSales": 1.25 + } + } +) +``` + +This will: + +- Increase `fullTime` from 8 to 12 (8 × 1.5) +- Increase `partTime` from 5 to 10 (5 × 2) +- Increase `totalSales` by 25% (multiply by 1.25) + +### Example 4: Creating new fields + +If a field doesn't exist, `$mul` creates it and sets it to 0. + +```javascript +db.stores.updateOne( + { "_id": "438db151-04b8-4422-aa97-acf94bc69cfc" }, + { + $mul: { + "sales.bonusPoints": 100, + "staff.overtimeHours": 40 + } + } +) +``` + +Both `bonusPoints` and `overtimeHours` will be created with value 0. + +### Example 5: Working with decimals + +Apply precise decimal multipliers for financial calculations. + +```javascript +db.stores.updateOne( + { "_id": "438db151-04b8-4422-aa97-acf94bc69cfc" }, + { + $mul: { + "sales.totalSales": 0.915 + } + } +) +``` + +### Example 6: Updating array elements + +Apply multipliers to specific elements within arrays using positional operators. + +```javascript +db.stores.updateOne( + { + "_id": "438db151-04b8-4422-aa97-acf94bc69cfc", + "sales.salesByCategory.categoryName": "Direct-Drive Turntables" + }, + { + $mul: { + "sales.salesByCategory.$.totalSales": 1.15 + } + } +) +``` + +### Example 7: Negative values and zero + +Handle negative multipliers and zero values. + +```javascript +db.stores.updateOne( + { "_id": "438db151-04b8-4422-aa97-acf94bc69cfc" }, + { + $mul: { + "sales.totalSales": -1, + "staff.totalStaff.fullTime": 0 + } + } +) +``` + +This will: + +- Make `totalSales` negative (useful for reversals) +- Set `fullTime` to 0 + +After applying a 1.5 multiplier to staff and 1.25 to sales, the document would be updated as follows: + +```json +{ + "_id": "438db151-04b8-4422-aa97-acf94bc69cfc", + "name": "Fourth Coffee | Turntable Boutique - Tromptown", + "staff": { + "totalStaff": { + "fullTime": 12, + "partTime": 10 + }, + "overtimeHours": 0 + }, + "sales": { + "totalSales": 31078.75, + "bonusPoints": 0, + "salesByCategory": [ + { + "categoryName": "Direct-Drive Turntables", + "totalSales": 28592.45 + } + ] + } +} +``` diff --git a/api-reference/operators/field-update/$rename.md b/api-reference/operators/field-update/$rename.md new file mode 100644 index 0000000..d98dfff --- /dev/null +++ b/api-reference/operators/field-update/$rename.md @@ -0,0 +1,202 @@ +--- +title: $rename +description: The $rename operator allows renaming fields in documents during update operations. +type: operators +category: field-update +--- + +# $rename + +The `$rename` operator is used to rename fields in documents during update operations. It removes the field with the old name and creates a new field with the specified name, preserving the original value. This operator is useful for restructuring document schemas or correcting field naming conventions. + +## Syntax + +```javascript +{ + $rename: { + : , + : , + ... + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The current name of the field to be renamed. | +| **`newName`** | The new name for the field. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Renaming top-level fields + +To rename the `name` field to `storeName` and `location` to `storeLocation`, use the $rename operator with both the fields. + +```javascript +db.stores.updateOne( + { "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" }, + { + $rename: { + "name": "storeName", + "location": "storeLocation" + } + } +) +``` + +### Example 2: Renaming nested fields + +You can also rename nested fields by using dot notation. + +```javascript +db.stores.updateOne( + { "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" }, + { + $rename: { + "location.lat": "location.latitude", + "location.lon": "location.longitude", + "staff.totalStaff.fullTime": "staff.totalStaff.fullTimeEmployees" + } + } +) +``` + +### Example 3: Bulk rename operations + +You can rename fields across multiple documents using `updateMany()`. + +```javascript +db.stores.updateMany( + {}, + { + $rename: { + "sales.totalSales": "sales.revenue", + "staff.totalStaff": "staff.employeeCount" + } + } +) +``` + +> [!Important] +> +> If the field specified in `$rename` does not exist, the operation will have no effect on that field. +> +> If the new field name already exists, the `$rename` operation will overwrite the existing field. +> +> The `$rename` operator cannot be used to rename array elements or fields within array elements. +> +> Field names cannot be empty strings or contain null characters. diff --git a/api-reference/operators/field-update/$setoninsert.md b/api-reference/operators/field-update/$setoninsert.md new file mode 100644 index 0000000..e97bb84 --- /dev/null +++ b/api-reference/operators/field-update/$setoninsert.md @@ -0,0 +1,332 @@ +--- +title: $setOnInsert +description: The $setOnInsert operator sets field values only when an upsert operation results in an insert of a new document. +type: operators +category: field-update +--- + +# $setOnInsert + +The `$setOnInsert` operator is used to set field values only when an upsert operation results in the insertion of a new document. If the document already exists and is being updated, the `$setOnInsert` operator has no effect. This operator is particularly useful for setting default values or initialization data that should only be applied when creating new documents. + +## Syntax + +```javascript +{ + $setOnInsert: { + : , + : , + ... + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The name of the field to set only on insert. Can be a top-level field or use dot notation for nested fields. | +| **`value`** | The value to assign to the field only when inserting a new document. Can be any valid BSON type. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic $setOnInsert usage + +To create or update a store record, but only set certain initialization fields when creating a new store. + +```javascript +db.stores.updateOne( + { "_id": "new-store-001" }, + { + $set: { + "name": "Trey Research Electronics - Downtown", + "sales.totalSales": 0 + }, + $setOnInsert: { + "createdDate": new Date(), + "status": "new", + "staff.totalStaff.fullTime": 0, + "staff.totalStaff.partTime": 0, + "version": 1 + } + }, + { upsert: true } +) +``` + +This operation returns the following result. + +```json +{ + acknowledged: true, + insertedId: 'new-store-001', + matchedCount: 0, + modifiedCount: Long("0"), + upsertedCount: 1 +} +``` + +Since the document with `_id: "new-store-001"` doesn't exist, this operation creates the following new document: + +```json +{ + "_id": "new-store-001", + "name": "Trey Research Electronics - Downtown", + "sales": { + "totalSales": 0 + }, + "createdDate": ISODate("2025-06-05T10:30:00.000Z"), + "status": "new", + "staff": { + "totalStaff": { + "fullTime": 0, + "partTime": 0 + } + }, + "version": 1 +} +``` + +### Example 2: $setOnInsert with existing document + +Now, let's try to upsert the same document again with different values: + +```javascript +db.stores.updateOne( + { "_id": "new-store-001" }, + { + $set: { + "name": "Trey Research Electronics - Downtown Branch", + "sales.totalSales": 5000 + }, + $setOnInsert: { + "createdDate": new Date(), + "status": "updated", + "staff.totalStaff.fullTime": 10, + "staff.totalStaff.partTime": 5, + "version": 2 + } + }, + { upsert: true } +) +``` + +Since the document already exists, only the `$set` operations will be applied, and `$setOnInsert` will be ignored: + +```json +{ + "_id": "new-store-001", + "name": "Trey Research Electronics - Downtown Branch", + "sales": { + "totalSales": 5000 + }, + "createdDate": ISODate("2025-06-05T10:30:00.000Z"), + "status": "new", + "staff": { + "totalStaff": { + "fullTime": 0, + "partTime": 0 + } + }, + "version": 1 +} +``` + +### Example 3: Complex $setOnInsert with nested objects + +You can use `$setOnInsert` to initialize complex nested structures: + +```javascript +db.stores.updateOne( + { "name": "Adatum Gaming Paradise - Mall Location" }, + { + $set: { + "location.lat": 35.6762, + "location.lon": 139.6503 + }, + $setOnInsert: { + "_id": "gaming-store-mall-001", + "createdDate": new Date(), + "status": "active", + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 12 + }, + "manager": "Alex Johnson", + "departments": ["gaming", "accessories", "repairs"] + }, + "sales": { + "totalSales": 0, + "salesByCategory": [] + }, + "operatingHours": { + "weekdays": "10:00-22:00", + "weekends": "09:00-23:00" + }, + "metadata": { + "version": 1, + "source": "store-management-system" + } + } + }, + { upsert: true } +) +``` + +### Example 4: Using $setOnInsert with arrays + +You can initialize arrays and complex data structures: + +```javascript +db.stores.updateOne( + { "address.city": "New Tech City" }, + { + $set: { + "name": "Future Electronics Hub", + "sales.totalSales": 25000 + }, + $setOnInsert: { + "_id": "future-electronics-001", + "establishedDate": new Date(), + "categories": ["electronics", "gadgets", "smart-home"], + "promotionEvents": [], + "ratings": { + average: 0, + count: 0, + reviews: [] + }, + "inventory": { + lastUpdated: new Date(), + totalItems: 0, + lowStockAlerts: [] + } + } + }, + { upsert: true } +) +``` + +> [!Important] +> +> The `$setOnInsert` operator only takes effect during upsert operations (`{ upsert: true }`). +> +> If the document exists, `$setOnInsert` fields are completely ignored. +> +> `$setOnInsert` is commonly used with `$set` to handle both update and insert scenarios in a single operation. +> +> You can combine `$setOnInsert` with other update operators like `$inc`, `$push`, etc. +> +> The `$setOnInsert` operator is ideal for setting creation timestamps, default values, and initialization data. diff --git a/api-reference/operators/geospatial/$box.md b/api-reference/operators/geospatial/$box.md new file mode 100644 index 0000000..89bfcaf --- /dev/null +++ b/api-reference/operators/geospatial/$box.md @@ -0,0 +1,280 @@ +--- +title: $box +description: The $box operator defines a rectangular area for geospatial queries using coordinate pairs. +type: operators +category: geospatial +--- + +# $box + +The `$box` operator defines a rectangular area for geospatial queries using two coordinate pairs. It's useful for finding locations within a rectangular geographical boundary. + +## Syntax + +```javascript +{ + : { + $geoWithin: { + $box: [ + [, ], + [, ] + ] + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `location field`| The field containing the geospatial data | +| `lower_left`| An array of [longitude, latitude] specifying the bottom-left corner | +| `upper_right`| An array of [longitude, latitude] specifying the top-right corner | + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { "lat": -74.0427, "lon": 160.8154 }, + "staff": { "employeeCount": { "fullTime": 9, "partTime": 18 } }, + "sales": { + "salesByCategory": [ { "categoryName": "Stockings", "totalSales": 25731 } ], + "revenue": 25731 + }, + "promotionEvents": [ + { + "eventName": "Mega Savings Extravaganza", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 6, "Day": 29 }, + "endDate": { "Year": 2023, "Month": 7, "Day": 7 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 16 }, + { "categoryName": "Tree Ornaments", "discountPercentage": 8 } + ] + }, + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 9, "Day": 27 }, + "endDate": { "Year": 2023, "Month": 10, "Day": 4 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 11 }, + { "categoryName": "Holiday Cards", "discountPercentage": 9 } + ] + }, + { + "eventName": "Massive Deal Mania", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 2 } + }, + "discounts": [ + { "categoryName": "Gift Bags", "discountPercentage": 21 }, + { "categoryName": "Bows", "discountPercentage": 19 } + ] + }, + { + "eventName": "Super Saver Soiree", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 1 } + }, + "discounts": [ + { "categoryName": "Tree Ornaments", "discountPercentage": 15 }, + { "categoryName": "Stockings", "discountPercentage": 14 } + ] + }, + { + "eventName": "Fantastic Savings Fiesta", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 24 }, + { "categoryName": "Gift Wrap", "discountPercentage": 16 } + ] + }, + { + "eventName": "Price Plunge Party", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 28 } + }, + "discounts": [ + { "categoryName": "Holiday Tableware", "discountPercentage": 13 }, + { "categoryName": "Holiday Cards", "discountPercentage": 11 } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Marvinfort", + "storeOpeningDate": { "$date": "2024-10-01T18:24:02.586Z" }, + "lastUpdated": { "$timestamp": { "t": 1730485442, "i": 1 } }, + "storeFeatures": 38 +} +``` + +### Example 1: Find stores within a geographic box + +The query retrieves up to 2 stores whose location falls inside the specified rectangular bounding box defined by two corner coordinates. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 2 - Find stores within a rectangular region + +The query returns all stores that fall within the rectangular region defined by these coordinates. + +```javascript +db.stores.find( + { + location: { + $geoWithin: { + $box: [ + [-142.0012, -51.3041], // Lower left corner + [123.3403, 70.1272] // Upper right corner + ] + } + } + }, + { + name: 1, + location: 1 + } +).limit(2) +``` + +The query returns all stores that fall within the rectangular region defined by these coordinates. + +```json +[ + { + "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", + "name": "Fourth Coffee | Storage Solution Gallery - Port Camilla", + "location": { + "lat": 78.3889, + "lon": 0.6784 + } + }, + { + "_id": "728c068a-638c-40af-9172-8ccfa7dddb49", + "name": "Contoso, Ltd. | Book Store - Lake Myron", + "location": { "lat": 29.416, "lon": 21.5231 } + } +] +``` diff --git a/api-reference/operators/geospatial/$center.md b/api-reference/operators/geospatial/$center.md new file mode 100644 index 0000000..a30c6c4 --- /dev/null +++ b/api-reference/operators/geospatial/$center.md @@ -0,0 +1,164 @@ +--- +title: $center +description: The $center operator specifies a circle using legacy coordinate pairs for $geoWithin queries. +type: operators +category: geospatial +--- + +# $center + +The `$center` operator specifies a circle using legacy coordinate pairs to be used in `$geoWithin` queries. It defines a circle for a geospatial query on a flat, Euclidean plane. + +## Syntax + +```javascript +{ + $geoWithin: { + $center: [ [ , ], ] + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `` | The x-coordinate of the circle's center point | +| `` | The y-coordinate of the circle's center point | +| `` | The radius of the circle in the same units as the coordinates | + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { "lat": -74.0427, "lon": 160.8154 }, + "staff": { "employeeCount": { "fullTime": 9, "partTime": 18 } }, + "sales": { + "salesByCategory": [ { "categoryName": "Stockings", "totalSales": 25731 } ], + "revenue": 25731 + }, + "promotionEvents": [ + { + "eventName": "Mega Savings Extravaganza", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 6, "Day": 29 }, + "endDate": { "Year": 2023, "Month": 7, "Day": 7 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 16 }, + { "categoryName": "Tree Ornaments", "discountPercentage": 8 } + ] + }, + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 9, "Day": 27 }, + "endDate": { "Year": 2023, "Month": 10, "Day": 4 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 11 }, + { "categoryName": "Holiday Cards", "discountPercentage": 9 } + ] + }, + { + "eventName": "Massive Deal Mania", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 2 } + }, + "discounts": [ + { "categoryName": "Gift Bags", "discountPercentage": 21 }, + { "categoryName": "Bows", "discountPercentage": 19 } + ] + }, + { + "eventName": "Super Saver Soiree", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 1 } + }, + "discounts": [ + { "categoryName": "Tree Ornaments", "discountPercentage": 15 }, + { "categoryName": "Stockings", "discountPercentage": 14 } + ] + }, + { + "eventName": "Fantastic Savings Fiesta", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 24 }, + { "categoryName": "Gift Wrap", "discountPercentage": 16 } + ] + }, + { + "eventName": "Price Plunge Party", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 28 } + }, + "discounts": [ + { "categoryName": "Holiday Tableware", "discountPercentage": 13 }, + { "categoryName": "Holiday Cards", "discountPercentage": 11 } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Marvinfort", + "storeOpeningDate": { "$date": "2024-10-01T18:24:02.586Z" }, + "lastUpdated": { "$timestamp": { "t": 1730485442, "i": 1 } }, + "storeFeatures": 38 +} +``` + +### Example 1 - Find stores within a circular area + +Let's find all stores within a 50-degree radius of 'First Up Consultants Microphone Bazaar' using our `stores` dataset. This query retrieves stores within a 50-degree radius of the First Up Consultants Microphone Bazaar location. + +```javascript +db.stores.find( + { + location: { + $geoWithin: { + $center: [[-112.7858, -29.1866], 50] + } + } + }, + { + name: 1, + city: 1, + location: 1, + _id: 0 + } +).limit(2) +``` + +The query returns stores within 50-degree radius, which could be useful for analyzing market coverage or planning delivery routes. + +```json +[ + { + "name": "Contoso, Ltd. | Baby Products Corner - Port Jerrold", + "location": { "lat": -72.7709, "lon": -24.3031 }, + "city": "Port Jerrold" + }, + { + "name": "VanArsdel, Ltd. | Smart Home Closet - Trystanport", + "location": { "lat": -64.5509, "lon": -28.7144 }, + "city": "Trystanport" + } +] +``` + +> [!IMPORTANT] +> The `$center` operator works on a flat, Euclidean plane. +> +> For more accurate Earth-like spherical calculations, use `$centerSphere` instead. +> +> The radius is specified in the same units as the coordinate system being used. diff --git a/api-reference/operators/geospatial/$centersphere.md b/api-reference/operators/geospatial/$centersphere.md new file mode 100644 index 0000000..01c17c8 --- /dev/null +++ b/api-reference/operators/geospatial/$centersphere.md @@ -0,0 +1,191 @@ +--- +title: $centerSphere +description: The $centerSphere operator specifies a circle using spherical geometry for $geoWithin queries. +type: operators +category: geospatial +--- + +# $centerSphere + +The `$centerSphere` operator specifies a circle using spherical geometry for `$geoWithin` queries. This operator is useful for geographic calculations that need to account for Earth's spherical shape. + +## Syntax + +```javascript +{ + $geoWithin: { + $centerSphere: [ [ , ], ] + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `` | The longitude of the circle's center point | +| `` | The latitude of the circle's center point | +| `` | The radius of the sphere in radians (divide distance in kilometers by 6371 to convert to radians) | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find stores within a circular area (calculation over earth's spherical shape) + +The example query finds two stores within approximately 1,000 kilometers (radius ≈ 0.157 radians) of the Wide World Importers Headphone Corner store location. The query can help identify nearby stores for regional marketing campaigns or supply chain optimization. + +```javascript +// Convert 1000km to radians: 1000/6371 ≈ 0.157 +db.stores.find( + { + location: { + $geoWithin: { + $centerSphere: [[-82.5543, -65.105], 0.157] + } + } + }, + { + _id: 0, + name: 1, + location: 1, + city: 1 + } +).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "name": "Fourth Coffee | Electronics Bazaar - O'Keefeburgh", + "location": { "lat": -64.5856, "lon": -115.5241 }, + "city": "O'Keefeburgh" + }, + { + "name": "Boulder Innovations | Footwear Outlet - West Sybleberg", + "location": { "lat": -72.73, "lon": -60.2306 }, + "city": "West Sybleberg" + } +] +``` + +> [!IMPORTANT] +> The `$centerSphere` operator calculates distances using spherical geometry, making it more accurate for Earth-based calculations than `$center`. +> +> The radius must be specified in radians. +> +> Coordinates should be specified in the order: [longitude, latitude]. +> +> If the geographic buffer extends beyond a UTM zone or crosses the international dateline, the results may be inaccurate or unpredictable. diff --git a/api-reference/operators/geospatial/$geointersects.md b/api-reference/operators/geospatial/$geointersects.md new file mode 100644 index 0000000..95c1e39 --- /dev/null +++ b/api-reference/operators/geospatial/$geointersects.md @@ -0,0 +1,207 @@ +--- +title: $geoIntersects +description: The $geoIntersects operator selects documents whose location field intersects with a specified GeoJSON object. +type: operators +category: geospatial +--- + +# $geoIntersects + +The `$geoIntersects` operator selects documents whose location field intersects with a specified GeoJSON object. This operator is useful when you want to find stores that intersect with a specific geographical area. + +## Syntax + +```javascript +{ + : { + $geoIntersects: { + $geometry: { + type: , + coordinates: + } + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `location field` | The field containing the GeoJSON object | +| `type` | The GeoJSON object type (for example, "Polygon", "MultiPolygon") | +| `coordinates` | The coordinates defining the GeoJSON object | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Find stores that geographically intersect + +For better performance, start with creating the required `2dsphere` index. + +```javascript +db.stores.createIndex({ "location": "2dsphere" }) +``` + +The example query find stores that intersect with a specific polygon area using the `stores` collection. This polygon encompasses several store locations from our dataset. + +```javascript +db.stores.find( + { + location: { + $geoIntersects: { + $geometry: { + type: "Polygon", + coordinates: [[ + [-80.0, -75.0], + [-80.0, -70.0], + [-55.0, -70.0], + [-55.0, -75.0], + [-80.0, -75.0] + ]] + } + } + } + }, + { + name: 1, + location: 1 + } +).limit(2) +``` + +The query returns stores, whose locations intersect with the Polygon contour defined by the coordinates. + +```json +[ + { + "_id": "6bba7117-d180-4584-b50c-a2f843e9c9ab", + "name": "Wide World Importers | Craft Supply Mart - Heaneybury", + "location": { "lat": -64.4843, "lon": -107.7003 }, + "city": "Heaneybury" + }, + { + "_id": "2fd37663-e0ff-41d0-9c5a-3aec86285daa", + "name": "Relecloud | Cleaning Supply Closet - Patiencehaven", + "location": { "lat": -70.6077, "lon": -105.9901 }, + "city": "Patiencehaven" + } +] +``` + +The $geointersects operator is useful for the following scenarios: + +- Finding stores within a specific geographical boundary +- Identifying service coverage areas +- Planning delivery routes diff --git a/api-reference/operators/geospatial/$geometry.md b/api-reference/operators/geospatial/$geometry.md new file mode 100644 index 0000000..f67c362 --- /dev/null +++ b/api-reference/operators/geospatial/$geometry.md @@ -0,0 +1,287 @@ +--- +title: $geometry +description: The $geometry operator specifies a GeoJSON geometry for geospatial queries. +type: operators +category: geospatial +--- + +# $geometry + +The `$geometry` operator specifies a GeoJSON geometry object for geospatial queries. It's used within other geospatial operators to define shapes and points for spatial calculations. + +## Syntax + +```javascript +{ + $geometry: { + type: , + coordinates: + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `type` | GeoJSON object type (Point, Polygon, MultiPolygon, etc.) | +| `coordinates` | Coordinates defining the GeoJSON object as an array | + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find nearest stores to point geometry + +For better performance, start with creating the required `2dsphere` index. + +```javascript +db.stores.createIndex({ location: "2dsphere" }) +``` + +The query retrieves up to two stores closest to the point at coordinates [46.2917, -62.6354], ordered by proximity. It uses the $near operator to sort results by distance from a specific point, helping find stores that are geographically nearest to a given location. + +```javascript +db.stores.find({ + location: { + $near: { + $geometry: { + type: "Point", + coordinates: [46.2917, -62.6354] + } + } + } +}, { + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "59c355e9-586c-44f8-bbaf-a87989142119", + "name": "Relecloud | Outdoor Furniture Shop - Chetside", + "location": { "lat": 46.188, "lon": -62.2789 } + }, + { + "_id": "d3a9cc23-e6ae-4806-93ac-1ade2f624742", + "name": "VanArsdel, Ltd. | Furniture Place - North Dustinside", + "location": { "lat": 47.3426, "lon": -62.4031 } + } +] +``` + +### Example 2: Find nearest stores to polygon geometry + +This query finds up to two stores whose locations intersect with a defined rectangular polygon bounded by coordinates from [-80.0, -75.0] to [-55.0, -70.0]. + +The `$geoIntersects` operator finds stores that overlap with or touch your polygon boundaries - perfect for identifying which locations interact with a specific geographic zone, whether they're fully inside it or just crossing the edge. + +```javascript +db.stores.find({ + location: { + $geoIntersects: { + $geometry: { + type: "Polygon", + coordinates: [[ + [-80.0, -75.0], // Bottom-left + [-80.0, -70.0], // Top-left + [-55.0, -70.0], // Top-right + [-55.0, -75.0], // Bottom-right + [-80.0, -75.0] // Close polygon + ]] + } + } + } +}, { + name: 1, + location: 1, + city: 1 +}).limit(2) +``` + +The first two results returned by this query. + +```json +[ + { + "_id": "6bba7117-d180-4584-b50c-a2f843e9c9ab", + "name": "Wide World Importers | Craft Supply Mart - Heaneybury", + "location": { "lat": -64.4843, "lon": -107.7003 }, + "city": "Heaneybury" + }, + { + "_id": "2fd37663-e0ff-41d0-9c5a-3aec86285daa", + "name": "Relecloud | Cleaning Supply Closet - Patiencehaven", + "location": { "lat": -70.6077, "lon": -105.9901 }, + "city": "Patiencehaven" + } +] +``` + +### Example 3: Find nearest stores to multi-polygon geometry + +The example retrieves up to two stores whose locations fall within either of the two defined rectangular regions (MultiPolygon): one near the coordinates [120.0, -13.0] to [125.0, -10.0], and another near [44.0, -64.0] to [48.0, -61.0]. + +It uses the $geoWithin operator with a MultiPolygon geometry to search for stores enclosed by any of the specified polygons, making it useful for querying across multiple nonadjacent geographic areas simultaneously. + +```javascript +db.stores.find({ + location: { + $geoWithin: { + $geometry: { + type: "MultiPolygon", + coordinates: [ + [[ + [120.0, -13.0], + [120.0, -10.0], + [125.0, -10.0], + [125.0, -13.0], + [120.0, -13.0] + ]], + [[ + [44.0, -64.0], + [44.0, -61.0], + [48.0, -61.0], + [48.0, -64.0], + [44.0, -64.0] + ]] + ] + } + } + } +}, { + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "6d70de9c-7b83-426d-81aa-f2173f97b64d", + "name": "Fabrikam, Inc. | Footwear Haven - Port Erling", + "location": { "lat": 45.641, "lon": -118.4963 } + }, + { + "_id": "96d48224-ce10-4a61-999a-8536d442f81a", + "name": "Wide World Importers | Eyewear Bazaar - West Oletachester", + "location": { "lat": 47.3461, "lon": -61.6605 } + } +] +``` diff --git a/api-reference/operators/geospatial/$geowithin.md b/api-reference/operators/geospatial/$geowithin.md new file mode 100644 index 0000000..323a7a8 --- /dev/null +++ b/api-reference/operators/geospatial/$geowithin.md @@ -0,0 +1,298 @@ +--- +title: $geoWithin +description: The $geoWithin operator selects documents whose location field is completely within a specified geometry. +type: operators +category: geospatial +--- + +# $geoWithin + +The `$geoWithin` operator selects documents whose location field falls completely within a specified geometry. This operator supports various shape operators including `$box`, `$polygon`, `$center`, and `$geometry`. + +## Syntax + +```javascript +// Using $box +{ + : { + $geoWithin: { + $box: [ [ ], [ ] ] + } + } +} + +// Using $center +{ + : { + $geoWithin: { + $center: [ [ , ], ] + } + } +} + +// Using $geometry +{ + : { + $geoWithin: { + $geometry: { + type: , + coordinates: + } + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `location field` | The field containing the location coordinates | +| `$box` | Two sets of coordinates defining opposite corners of a box | +| `$center` | Center point coordinates and radius in degrees | +| `$geometry` | GeoJSON object defining the boundary | + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find stores defined by $box + +For getting better performance, ensure you have a `2dsphere` index. + +```javascript +db.stores.createIndex({ location: "2dsphere" }) +``` + +This query finds stores that are located within a specific rectangular area on a map, defined by a box (bounding rectangle). + +```javascript +db.stores.find({ + location: { + $geoWithin: { + $box: [ + [65.0, 65.0], // Bottom left corner + [75.0, 75.0] // Top right corner + ] + } + } +}, { + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "location": { + "lat": 70.1272, + "lon": 69.7296, + "address": "123 Entertainment Blvd", + "city": "East Linwoodbury" + } + }, + { + "_id": "fc286536-cb94-45aa-b975-7040fde04cf7", + "name": "First Up Consultants | Medical Supply Corner - South Elnoraview", + "location": { + "lat": 72.2184, + "lon": 68.9829 + } + } +] +``` + +### Example 2: Find stores defined by $center + +The query uses a `$geoWithin` operator to find stores within a circular area defined by a center point and a radius. + +```javascript +db.stores.find({ + 'location': { + $geoWithin: { + $center: [ + [-82.5543, -65.105], // Center point (Wide World Importers location) + 5 // Radius in degrees + ] + } + } +}, { + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "3e962dd0-dffb-49d6-8a96-1d29fa1553d2", + "name": "Tailwind Traders | Book Center - Lake Marlen", + "location": { "lat": -85.4034, "lon": -65.9189 } + }, + { + "_id": "7e442816-be4c-4919-8f67-d1e9162a511f", + "name": "Proseware, Inc. | Outdoor Furniture Bargains - North Obieberg", + "location": { "lat": -84.1013, "lon": -69.5717 } + } +] +``` + +### Example 3: Find stores defined by $geometry + +This query finds up to two stores whose location falls within the defined rectangular polygon. + +```javascript +db.stores.find({ + 'location': { + $geoWithin: { + $geometry: { + type: "Polygon", + coordinates: [[ + [-85.0, -70.0], + [-85.0, -60.0], + [-75.0, -60.0], + [-75.0, -70.0], + [-85.0, -70.0] + ]] + } + } + } +}, { + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "66fd4cdd-ffc3-44b6-81d9-6d5e9c1f7f9a", + "name": "Trey Research | Health Food Center - North Michelle", + "location": { "lat": -77.9951, "lon": -62.7339 } + }, + { + "_id": "ea3f775b-f977-4827-ada4-ca7fd8ed0cd4", + "name": "VanArsdel, Ltd. | Outdoor Equipment Pantry - Port Aleenton", + "location": { "lat": -76.4516, "lon": -67.2051 } + } +] +``` diff --git a/api-reference/operators/geospatial/$maxdistance.md b/api-reference/operators/geospatial/$maxdistance.md new file mode 100644 index 0000000..8001960 --- /dev/null +++ b/api-reference/operators/geospatial/$maxdistance.md @@ -0,0 +1,158 @@ +--- +title: $maxDistance +description: The $maxDistance operator specifies the maximum distance that can exist between two points in a geospatial query. +type: operators +category: geospatial +--- + +# $maxDistance + +The `$maxDistance` operator is used in geospatial queries to specify the maximum distance (in meters) that can exist between two points. It pairs well with `$near` for radius-based location searches. + +## Syntax + +```javascript +{ + : { + $near: { + $geometry: { + type: "Point", + coordinates: [, ] + }, + $maxDistance: + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `location field` | The field containing the geospatial data | +| `coordinates` | An array of [longitude, latitude] specifying the center point | +| `$maxDistance`| Maximum distance in meters from the center point | + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { "lat": -74.0427, "lon": 160.8154 }, + "staff": { "employeeCount": { "fullTime": 9, "partTime": 18 } }, + "sales": { + "salesByCategory": [ { "categoryName": "Stockings", "totalSales": 25731 } ], + "revenue": 25731 + }, + "promotionEvents": [ + { + "eventName": "Mega Savings Extravaganza", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 6, "Day": 29 }, + "endDate": { "Year": 2023, "Month": 7, "Day": 7 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 16 }, + { "categoryName": "Tree Ornaments", "discountPercentage": 8 } + ] + }, + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 9, "Day": 27 }, + "endDate": { "Year": 2023, "Month": 10, "Day": 4 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 11 }, + { "categoryName": "Holiday Cards", "discountPercentage": 9 } + ] + }, + { + "eventName": "Massive Deal Mania", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 2 } + }, + "discounts": [ + { "categoryName": "Gift Bags", "discountPercentage": 21 }, + { "categoryName": "Bows", "discountPercentage": 19 } + ] + }, + { + "eventName": "Super Saver Soiree", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 1 } + }, + "discounts": [ + { "categoryName": "Tree Ornaments", "discountPercentage": 15 }, + { "categoryName": "Stockings", "discountPercentage": 14 } + ] + }, + { + "eventName": "Fantastic Savings Fiesta", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 24 }, + { "categoryName": "Gift Wrap", "discountPercentage": 16 } + ] + }, + { + "eventName": "Price Plunge Party", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 28 } + }, + "discounts": [ + { "categoryName": "Holiday Tableware", "discountPercentage": 13 }, + { "categoryName": "Holiday Cards", "discountPercentage": 11 } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Marvinfort", + "storeOpeningDate": { "$date": "2024-10-01T18:24:02.586Z" }, + "lastUpdated": { "$timestamp": { "t": 1730485442, "i": 1 } }, + "storeFeatures": 38 +} +``` + +### Example 1: Find stores near a specific location + +The query retrieves up to two stores within a 10 km radius of the given point coordinates [-77.9951, -62.7339]. + +```javascript +db.stores.find({ + location: { + $near: { + $geometry: { + type: "Point", + coordinates: [-77.9951,-62.7339] + }, + $maxDistance: 10000 // 10 kilometers in meters + } + } +}, +{ + name: 1, + location: 1 +}).limit(2) +``` + +The query returns the following result. + +```json +[ + { + "_id": "66fd4cdd-ffc3-44b6-81d9-6d5e9c1f7f9a", + "name": "Trey Research | Health Food Center - North Michelle", + "location": { "lat": -77.9951, "lon": -62.7339 } + } +] +``` diff --git a/api-reference/operators/geospatial/$mindistance.md b/api-reference/operators/geospatial/$mindistance.md new file mode 100644 index 0000000..61915f1 --- /dev/null +++ b/api-reference/operators/geospatial/$mindistance.md @@ -0,0 +1,163 @@ +--- +title: $minDistance +description: The $minDistance operator specifies the minimum distance that must exist between two points in a geospatial query. +type: operators +category: geospatial +--- + +# $minDistance + +The `$minDistance` operator is used in geospatial queries to specify the minimum distance (in meters) that must exist between two points. It's useful for finding locations outside a certain radius. + +## Syntax + +```javascript +{ + : { + $near: { + $geometry: { + type: "Point", + coordinates: [, ] + }, + $minDistance: + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|------|-------------| +| `location field` | The field containing the geospatial data | +| `coordinates` | An array of [longitude, latitude] specifying the center point | +| `$minDistance` | Minimum distance in meters from the center point | + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { "lat": -74.0427, "lon": 160.8154 }, + "staff": { "employeeCount": { "fullTime": 9, "partTime": 18 } }, + "sales": { + "salesByCategory": [ { "categoryName": "Stockings", "totalSales": 25731 } ], + "revenue": 25731 + }, + "promotionEvents": [ + { + "eventName": "Mega Savings Extravaganza", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 6, "Day": 29 }, + "endDate": { "Year": 2023, "Month": 7, "Day": 7 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 16 }, + { "categoryName": "Tree Ornaments", "discountPercentage": 8 } + ] + }, + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 9, "Day": 27 }, + "endDate": { "Year": 2023, "Month": 10, "Day": 4 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 11 }, + { "categoryName": "Holiday Cards", "discountPercentage": 9 } + ] + }, + { + "eventName": "Massive Deal Mania", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 2 } + }, + "discounts": [ + { "categoryName": "Gift Bags", "discountPercentage": 21 }, + { "categoryName": "Bows", "discountPercentage": 19 } + ] + }, + { + "eventName": "Super Saver Soiree", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 1 } + }, + "discounts": [ + { "categoryName": "Tree Ornaments", "discountPercentage": 15 }, + { "categoryName": "Stockings", "discountPercentage": 14 } + ] + }, + { + "eventName": "Fantastic Savings Fiesta", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 24 }, + { "categoryName": "Gift Wrap", "discountPercentage": 16 } + ] + }, + { + "eventName": "Price Plunge Party", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 28 } + }, + "discounts": [ + { "categoryName": "Holiday Tableware", "discountPercentage": 13 }, + { "categoryName": "Holiday Cards", "discountPercentage": 11 } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Marvinfort", + "storeOpeningDate": { "$date": "2024-10-01T18:24:02.586Z" }, + "lastUpdated": { "$timestamp": { "t": 1730485442, "i": 1 } }, + "storeFeatures": 38 +} +``` + +### Example 1: Finding stores by minimum distance from a reference Point + +The example query allow to find stores that are at least 500 kilometers away from point coordinate [69.7296, 70.1272]. + +```javascript +db.stores.find({ + location: { + $near: { + $geometry: { + type: "Point", + coordinates: [69.7296, 70.1272] // Proseware Home Entertainment Hub location + }, + $minDistance: 500000 // 500 kilometers in meters + } + } +}, +{ + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "9d9d768b-4daf-4126-af15-a963bd3b88aa", + "name": "First Up Consultants | Perfume Gallery - New Verniceshire", + "location": { "lat": 36.0762, "lon": 98.7799 } + }, + { + "_id": "76b03913-37e3-4779-b3b8-0f654c1ae3e7", + "name": "Fabrikam, Inc. | Turntable Depot - Schinnershire", + "location": { "lat": 37.5534, "lon": 81.6805 } + } +] +``` diff --git a/api-reference/operators/geospatial/$near.md b/api-reference/operators/geospatial/$near.md new file mode 100644 index 0000000..0a3a375 --- /dev/null +++ b/api-reference/operators/geospatial/$near.md @@ -0,0 +1,201 @@ +--- +title: $near +description: The $near operator returns documents with location fields that are near a specified point, sorted by distance. +type: operators +category: geospatial +--- + +# $near + +The `$near` operator returns documents whose location field is near a specified point, sorted by distance. It requires a '2dsphere' index and returns documents from nearest to farthest. + +## Syntax + +```javascript +{ + : { + $near: { + $geometry: { + type: "Point", + coordinates: [, ] + }, + $maxDistance: , + $minDistance: + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `location field` | The field containing the GeoJSON Point | +| `$geometry` | GeoJSON Point object specifying the center point | +| `$maxDistance` | Optional. Maximum distance in meters from the center point | +| `$minDistance` | Optional. Minimum distance in meters from the center point | + +## Prerequisite + +For better performance, start with creating the required `2dsphere` index. + +```javascript +db.stores.createIndex({ "location": "2dsphere" }) +``` + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { "lat": -74.0427, "lon": 160.8154 }, + "staff": { "employeeCount": { "fullTime": 9, "partTime": 18 } }, + "sales": { + "salesByCategory": [ { "categoryName": "Stockings", "totalSales": 25731 } ], + "revenue": 25731 + }, + "promotionEvents": [ + { + "eventName": "Mega Savings Extravaganza", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 6, "Day": 29 }, + "endDate": { "Year": 2023, "Month": 7, "Day": 7 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 16 }, + { "categoryName": "Tree Ornaments", "discountPercentage": 8 } + ] + }, + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 9, "Day": 27 }, + "endDate": { "Year": 2023, "Month": 10, "Day": 4 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 11 }, + { "categoryName": "Holiday Cards", "discountPercentage": 9 } + ] + }, + { + "eventName": "Massive Deal Mania", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 2 } + }, + "discounts": [ + { "categoryName": "Gift Bags", "discountPercentage": 21 }, + { "categoryName": "Bows", "discountPercentage": 19 } + ] + }, + { + "eventName": "Super Saver Soiree", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 1 } + }, + "discounts": [ + { "categoryName": "Tree Ornaments", "discountPercentage": 15 }, + { "categoryName": "Stockings", "discountPercentage": 14 } + ] + }, + { + "eventName": "Fantastic Savings Fiesta", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 24 }, + { "categoryName": "Gift Wrap", "discountPercentage": 16 } + ] + }, + { + "eventName": "Price Plunge Party", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 28 } + }, + "discounts": [ + { "categoryName": "Holiday Tableware", "discountPercentage": 13 }, + { "categoryName": "Holiday Cards", "discountPercentage": 11 } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Marvinfort", + "storeOpeningDate": { "$date": "2024-10-01T18:24:02.586Z" }, + "lastUpdated": { "$timestamp": { "t": 1730485442, "i": 1 } }, + "storeFeatures": 38 +} +``` + +### Example 1: Basic proximity search + +The query retrieves the two closest stores to a specific geographic point (70.1272, 69.7296) using geospatial search. This query searches for locations closest to the given point and returns stores in ascending order of distance from the point. + +```javascript +db.stores.find({ + 'location': { + $near: { + $geometry: { + type: "Point", + coordinates: [69.7296, 70.1272] // [longitude, latitude] + } + } + } +}, { + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "3882eb86-5dd6-4701-9640-f670ccb67859", + "name": "Fourth Coffee | DJ Equipment Stop - Schuppestad", + "location": { "lat": 69.4923, "lon": 70.1851 } + }, + { + "_id": "bbec6d3e-1666-45b4-8803-8b7ef8544845", + "name": "First Up Consultants | Baby Products Bargains - South Keenan", + "location": { "lat": 69.2158, "lon": 70.3328 } + } +] +``` + +### Example 2: Using both Min and Max distance + +The query retrieves stores within a 20 km to 200 km range from a specified point and calculates their distances in kilometers. This query searches in a "donut-shaped" area - finding stores that are at least 20 meters away but no more than 200 meters from the specified point. + +```javascript +db.stores.aggregate([ + { + $geoNear: { + near: { + type: "Point", + coordinates: [70.3328, 69.2158] + }, + distanceField: "distance", + minDistance: 20, + maxDistance: 200, + spherical: true + } + }, + { + $project: { + name: 1, + location: 1, + distanceKm: { $divide: ["$distance", 1000] }, + _id: 0 + } + }, + { $limit: 2 } +]) +``` diff --git a/api-reference/operators/geospatial/$nearsphere.md b/api-reference/operators/geospatial/$nearsphere.md new file mode 100644 index 0000000..e903101 --- /dev/null +++ b/api-reference/operators/geospatial/$nearsphere.md @@ -0,0 +1,213 @@ +--- +title: $nearSphere +description: The $nearSphere operator returns documents whose location fields are near a specified point on a sphere, sorted by distance on a spherical surface. +type: operators +category: geospatial +--- + +# $nearSphere + +The `$nearSphere` operator returns documents with location fields near a specified point on a sphere, calculating distances using spherical geometry. The operator is more accurate for Earth-based calculations than `$near`. + +## Syntax + +```javascript +{ + : { + $nearSphere: { + $geometry: { + type: "Point", + coordinates: [, ] + }, + $maxDistance: , + $minDistance: + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `location field` | The field containing the GeoJSON Point | +| `$geometry` | GeoJSON Point object specifying the center point | +| `$maxDistance` | Optional. Maximum distance in meters on a spherical surface | +| `$minDistance` | Optional. Minimum distance in meters on a spherical surface | + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { "lat": -74.0427, "lon": 160.8154 }, + "staff": { "employeeCount": { "fullTime": 9, "partTime": 18 } }, + "sales": { + "salesByCategory": [ { "categoryName": "Stockings", "totalSales": 25731 } ], + "revenue": 25731 + }, + "promotionEvents": [ + { + "eventName": "Mega Savings Extravaganza", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 6, "Day": 29 }, + "endDate": { "Year": 2023, "Month": 7, "Day": 7 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 16 }, + { "categoryName": "Tree Ornaments", "discountPercentage": 8 } + ] + }, + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 9, "Day": 27 }, + "endDate": { "Year": 2023, "Month": 10, "Day": 4 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 11 }, + { "categoryName": "Holiday Cards", "discountPercentage": 9 } + ] + }, + { + "eventName": "Massive Deal Mania", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 2 } + }, + "discounts": [ + { "categoryName": "Gift Bags", "discountPercentage": 21 }, + { "categoryName": "Bows", "discountPercentage": 19 } + ] + }, + { + "eventName": "Super Saver Soiree", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 1 } + }, + "discounts": [ + { "categoryName": "Tree Ornaments", "discountPercentage": 15 }, + { "categoryName": "Stockings", "discountPercentage": 14 } + ] + }, + { + "eventName": "Fantastic Savings Fiesta", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 24 }, + { "categoryName": "Gift Wrap", "discountPercentage": 16 } + ] + }, + { + "eventName": "Price Plunge Party", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 28 } + }, + "discounts": [ + { "categoryName": "Holiday Tableware", "discountPercentage": 13 }, + { "categoryName": "Holiday Cards", "discountPercentage": 11 } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Marvinfort", + "storeOpeningDate": { "$date": "2024-10-01T18:24:02.586Z" }, + "lastUpdated": { "$timestamp": { "t": 1730485442, "i": 1 } }, + "storeFeatures": 38 +} +``` + +For better performance, start with creating the required `2dsphere` index. + +```javascript +db.stores.createIndex({ "location": "2dsphere" }) +``` + +### Example 1: Basic spherical search + +The query retrieves stores that are closest to a specified Point (-141.9922, 16.8331) on a spherical (Earth-like) surface. + +```javascript +db.stores.find({ + 'location': { + $nearSphere: { + $geometry: { + type: "Point", + coordinates: [-141.9922, 16.8331] + } + } + } +}, { + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "643b2756-c22d-4063-9777-0945b9926346", + "name": "Contoso, Ltd. | Outdoor Furniture Corner - Pagacfort", + "location": { + "type": "Point", + "coordinates": [152.1353, -89.8688] + } + }, + { + "_id": "daa71e60-75d4-4e03-8b45-9df59af0811f", + "name": "First Up Consultants | Handbag Corner - South Salvatore", + "location": { + "type": "Point", + "coordinates": [150.2305, -89.8431] + } + } +] +``` + +### Example 2: Complex distance analysis + +This query retrieves stores between 20 meter and 200 meter from Point (65.3765, -44.8674). The query searches in a "donut-shaped" area - finding stores that are at least 20 meters away but no more than 200 meters from the specified point. + +```javascript +db.stores.aggregate([ + { + $geoNear: { + near: { + type: "Point", + coordinates: [65.3765, -44.8674] + }, + distanceField: "sphericalDistance", + minDistance: 20, + maxDistance: 200, + spherical: true + } + }, + { + $project: { + name: 1, + location: 1, + distanceKm: { $divide: ["$sphericalDistance", 1000] }, + _id: 0 + } + }, + { + $limit: 2 + } +]) +``` + +Key difference between the operator `$nearSphere` and `$near`. + +* Former uses spherical geometry for distance calculations. +* Former is more accurate for Earth-based distance calculations. +* Former is better for applications requiring precise global distance calculations diff --git a/api-reference/operators/geospatial/$polygon.md b/api-reference/operators/geospatial/$polygon.md new file mode 100644 index 0000000..a26d3bf --- /dev/null +++ b/api-reference/operators/geospatial/$polygon.md @@ -0,0 +1,173 @@ +--- +title: $polygon +description: The $polygon operator defines a polygon for geospatial queries, allowing you to find locations within an irregular shape. +type: operators +category: geospatial +--- + +# $polygon + +The `$polygon` operator defines a polygon for geospatial queries, allowing you to find locations within an irregular shape. The operator is useful for querying locations within complex geographical boundaries. + +## Syntax + +```javascript +{ + : { + $geoWithin: { + $geometry: { + type: "Polygon", + coordinates: [ + [[, ], ..., [, ], [, ]] + ] + } + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `location field` | The field containing the geospatial data | +| `coordinates` | An array of coordinate pairs forming the polygon. The first and last points must be identical to close the polygon | + +## Examples + +Let's understand the usage with sample json from `stores` dataset. + +```json +{ + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "location": { "lat": -74.0427, "lon": 160.8154 }, + "staff": { "employeeCount": { "fullTime": 9, "partTime": 18 } }, + "sales": { + "salesByCategory": [ { "categoryName": "Stockings", "totalSales": 25731 } ], + "revenue": 25731 + }, + "promotionEvents": [ + { + "eventName": "Mega Savings Extravaganza", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 6, "Day": 29 }, + "endDate": { "Year": 2023, "Month": 7, "Day": 7 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 16 }, + { "categoryName": "Tree Ornaments", "discountPercentage": 8 } + ] + }, + { + "eventName": "Incredible Discount Days", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 9, "Day": 27 }, + "endDate": { "Year": 2023, "Month": 10, "Day": 4 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 11 }, + { "categoryName": "Holiday Cards", "discountPercentage": 9 } + ] + }, + { + "eventName": "Massive Deal Mania", + "promotionalDates": { + "startDate": { "Year": 2023, "Month": 12, "Day": 26 }, + "endDate": { "Year": 2024, "Month": 1, "Day": 2 } + }, + "discounts": [ + { "categoryName": "Gift Bags", "discountPercentage": 21 }, + { "categoryName": "Bows", "discountPercentage": 19 } + ] + }, + { + "eventName": "Super Saver Soiree", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 3, "Day": 25 }, + "endDate": { "Year": 2024, "Month": 4, "Day": 1 } + }, + "discounts": [ + { "categoryName": "Tree Ornaments", "discountPercentage": 15 }, + { "categoryName": "Stockings", "discountPercentage": 14 } + ] + }, + { + "eventName": "Fantastic Savings Fiesta", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 6, "Day": 23 }, + "endDate": { "Year": 2024, "Month": 6, "Day": 30 } + }, + "discounts": [ + { "categoryName": "Stockings", "discountPercentage": 24 }, + { "categoryName": "Gift Wrap", "discountPercentage": 16 } + ] + }, + { + "eventName": "Price Plunge Party", + "promotionalDates": { + "startDate": { "Year": 2024, "Month": 9, "Day": 21 }, + "endDate": { "Year": 2024, "Month": 9, "Day": 28 } + }, + "discounts": [ + { "categoryName": "Holiday Tableware", "discountPercentage": 13 }, + { "categoryName": "Holiday Cards", "discountPercentage": 11 } + ] + } + ], + "company": "Lakeshore Retail", + "city": "Marvinfort", + "storeOpeningDate": { "$date": "2024-10-01T18:24:02.586Z" }, + "lastUpdated": { "$timestamp": { "t": 1730485442, "i": 1 } }, + "storeFeatures": 38 +} +``` + +### Example 1 - Search within a polygon + +The query retrieves stores that fall inside a custom polygon region based on the coordinates provided. + +```javascript +db.stores.find({ + location: { + $geoWithin: { + $geometry: { + type: "Polygon", + coordinates: [[ + [-141.9922, 16.8331], // VanArsdel Picture Frame Store + [-112.7858, -29.1866], // First Up Consultants Microphone Bazaar + [-38.4071, -47.2548], // Fabrikam Car Accessory Outlet + [-141.9922, 16.8331] // Close the polygon by repeating first point + ]] + } + } + } +}, +{ + name: 1, + location: 1 +}).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "4a417727-a002-4c80-a01f-bc9526b300a5", + "name": "Northwind Traders | Bed and Bath Deals - East Duane", + "location": { + "type": "Point", + "coordinates": [-46.1444, -60.9697] + } + }, + { + "_id": "1e27040c-7242-4970-8893-e5738e1bc1ca", + "name": "Northwind Traders | Seasonal Decoration Bazaar - Cassidyberg", + "location": { + "type": "Point", + "coordinates": [-44.3617, -81.2186] + } + } +] +``` diff --git a/api-reference/operators/literal-expression/$literal.md b/api-reference/operators/literal-expression/$literal.md new file mode 100644 index 0000000..51e357d --- /dev/null +++ b/api-reference/operators/literal-expression/$literal.md @@ -0,0 +1,278 @@ +--- +title: $literal +description: The $literal operator returns the specified value without parsing it as an expression, allowing literal values to be used in aggregation pipelines. +type: operators +category: literal-expression +--- + +# $literal + +The `$literal` operator returns the specified value without parsing it as an expression. This operator is useful when you need to include literal values that might otherwise be interpreted as field names, operators, or expressions in your aggregation pipeline. It ensures that the value is treated as a constant rather than being evaluated. + +## Syntax + +```javascript +{ + $literal: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | Any value that should be returned as-is without interpretation. This can be a string, number, boolean, array, object, or null. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Adding literal status fields + +This query demonstrates adding literal status information to store documents, including literal strings that might otherwise be interpreted as field names or operators. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} }, + { + $project: { + name: 1, + totalSales: "$sales.salesByCategory.totalSales", + status: { $literal: "Active" }, + reviewStatus: { $literal: "$pending" }, + priority: { $literal: 1 }, + metadata: { + $literal: { + lastUpdated: "2024-06-13", + source: "automated-system" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "totalSales": 37701, + "status": "Active", + "reviewStatus": "$pending", + "priority": 1, + "metadata": { + "lastUpdated": "2024-06-13", + "source": "automated-system" + } + } +] +``` + +### Example 2: Creating literal arrays and conditional values + +This query shows how to use `$literal` with arrays and in conditional expressions to ensure values are not interpreted as operators. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + totalSales: "$sales.salesByCategory.totalSales", + performanceCategory: { + $cond: { + if: { $gte: ["$sales.totalSales", 100000] }, + then: { $literal: "High Performer" }, + else: { $literal: "Standard" } + } + }, + tags: { $literal: ["$featured", "$promoted", "$new"] }, + searchKeywords: { + $literal: { + "$or": ["electronics", "entertainment"], + "$and": ["home", "theater"] + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "totalSales": 160000, + "performanceCategory": "High Performer", + "tags": ["$featured", "$promoted", "$new"], + "searchKeywords": { + "$or": ["electronics", "entertainment"], + "$and": ["home", "theater"] + } + } +] +``` + +### Example 3: Literal null and boolean values + +This query demonstrates using `$literal` with null values and booleans, especially useful when these values need to be explicitly set rather than computed. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "e6895a31-a5cd-4103-8889-3b95a864e5a6"} }, + { + $project: { + name: 1, + totalSales: "$sales.salesByCategory.totalSales", + specialOffer: { $literal: null }, + isOnline: { $literal: false }, + hasInventory: { $literal: true }, + calculationFormula: { $literal: "$multiply: [price, quantity]" }, + ratingSystem: { + $literal: { + min: 0, + max: 5, + default: null + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "e6895a31-a5cd-4103-8889-3b95a864e5a6", + "name": "VanArsdel, Ltd. | Picture Frame Store - Port Clevelandton", + "totalSales": 17676, + "specialOffer": null, + "isOnline": false, + "hasInventory": true, + "calculationFormula": "$multiply: [price, quantity]", + "ratingSystem": { + "min": 0, + "max": 5, + "default": null + } + } +] +``` diff --git a/api-reference/operators/logical-query/$and.md b/api-reference/operators/logical-query/$and.md new file mode 100644 index 0000000..cc9f590 --- /dev/null +++ b/api-reference/operators/logical-query/$and.md @@ -0,0 +1,246 @@ +--- +title: $and +description: The $and operator joins multiple query clauses and returns documents that match all specified conditions. +type: operators +category: logical-query +--- + +# $and + +The `$and` operator performs a logical AND operation on an array of expressions and retrieves documents that satisfy all the expressions. + +## Syntax + +```javascript +{ + $and: [{ + < expression1 > + }, { + < expression2 > + }, ..., { + < expressionN > + }] +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `expression` | An array of expressions that must all be true for a document to be included in the results | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Use AND operator as logical-query + +This query filters for stores where the number of full-time employees is greater than 10 and part-time employees is less than 15 using the `$and` operator. It projects only the `name` and `staff` fields and limits the result to three records. + +```javascript +db.stores.find({ + $and: [{ + "staff.employeeCount.fullTime": { + $gt: 10 + } + }, { + "staff.employeeCount.partTime": { + $lt: 15 + } + }] +}, { + "name": 1, + "staff": 1 +}).limit(3) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "e60c807b-d31c-4903-befb-5d608f260ba3", + "name": "Wide World Importers | Appliance Emporium - Craigfort", + "staff": { + "totalStaff": { + "fullTime": 11, + "partTime": 8 + } + } + }, + { + "_id": "70032165-fded-47b4-84a3-8d9c18a4d1e7", + "name": "Northwind Traders | Picture Frame Bazaar - Lake Joesph", + "staff": { + "totalStaff": { + "fullTime": 14, + "partTime": 0 + } + } + }, + { + "_id": "dda2a7d2-6984-40cc-bbea-4cbfbc06d8a3", + "name": "Contoso, Ltd. | Home Improvement Closet - Jaskolskiview", + "staff": { + "totalStaff": { + "fullTime": 16, + "partTime": 8 + } + } + } +] +``` + +### Example 2: Use AND operator as boolean-expression to find stores with high sales and sufficient staff + +This query finds stores that have both total sales greater than 100,000 and more than 30 total staff members. + +```javascript +db.stores.aggregate([ + { + $project: { + name: 1, + totalSales: "$sales.totalSales", + totalStaff: { + $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] + }, + meetsHighPerformanceCriteria: { + $and: [ + { $gt: ["$sales.totalSales", 100000] }, + { $gt: [{ $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] }, 30] } + ] + } + } + }, + { $limit: 2 } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "totalStaff": 31, + "meetsHighPerformanceCriteria": false + }, + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "totalStaff": 27, + "meetsHighPerformanceCriteria": false + } +] +``` diff --git a/api-reference/operators/logical-query/$nor.md b/api-reference/operators/logical-query/$nor.md new file mode 100644 index 0000000..ed99b22 --- /dev/null +++ b/api-reference/operators/logical-query/$nor.md @@ -0,0 +1,266 @@ +--- +title: $nor +description: The $nor operator performs a logical NOR on an array of expressions and retrieves documents that fail all the conditions. +type: operators +category: logical-query +--- + +# $nor + +The `$nor` operator performs a logical NOR operation on an array of expressions and selects documents that fail all the specified expressions. + +## Syntax + +```javascript +{ + $nor: [{ + < expression1 > + }, { + < expression2 > + }, ..., { + < expressionN > + }] +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `expression` | An array of expressions, all of which must be false for a document to be included | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic NOR operation + +To find stores that neither have more than 15 full-time staff nor more than 20 part-time staff, run a query with the $nor operator on both the conditions. Then, project only the name and staff fields from the stores in the result set. + +```javascript +db.stores.find({ + $nor: [{ + "staff.totalStaff.fullTime": { + $gt: 15 + } + }, { + "staff.totalStaff.partTime": { + $gt: 20 + } + }] +}, { + "name": 1, + "staff": 1 +}) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "staff": { + "totalStaff": { + "fullTime": 9, + "partTime": 18 + } + } + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "name": "Lakeshore Retail | Home Decor Hub - Franciscoton", + "staff": { + "totalStaff": { + "fullTime": 7, + "partTime": 6 + } + } + } +] +``` + +### Example 2: Complex NOR operation + +To find stores without sales over $100,000, without sales of "Digital Watches", or without promotions in September 2024, run a query using the $nor operator on all three conditions. Lastly, project only the name, sales and promotion events from the stores in the result set. + +```javascript +db.stores.find({ + $nor: [{ + "sales.totalSales": { + $gt: 100000 + } + }, { + "sales.salesByCategory.categoryName": "Digital Watches" + }, { + "promotionEvents": { + $elemMatch: { + "promotionalDates.startDate.Month": 9, + "promotionalDates.startDate.Year": 2024 + } + } + }] +}, { + "name": 1, + "sales": 1, + "promotionEvents": 1 +}) +``` + +One of the results returned by this query is: + +```json +[ + { + "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", + "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", + "sales": { + "salesByCategory": [ + { + "categoryName": "DJ Headphones", + "totalSales": 35921 + } + ], + "fullSales": 3700 + }, + "promotionEvents": [ + { + "eventName": "Bargain Blitz Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 2, + "Day": 18 + } + }, + "discounts": [ + { + "categoryName": "DJ Turntables", + "discountPercentage": 18 + }, + { + "categoryName": "DJ Mixers", + "discountPercentage": 15 + } + ] + } + ] + } +] +``` diff --git a/api-reference/operators/logical-query/$not.md b/api-reference/operators/logical-query/$not.md new file mode 100644 index 0000000..861c56e --- /dev/null +++ b/api-reference/operators/logical-query/$not.md @@ -0,0 +1,233 @@ +--- +title: $not +description: The $not operator performs a logical NOT operation on a specified expression, selecting documents that don't match the expression. +type: operators +category: logical-query +--- + +# $not + +The `$not` operator performs a logical NOT operation on a specified expression and selects documents that don't match the expression. + +## Syntax + +```javascript +{ + field: { + $not: { + < operator - expression > + } + } +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `operator-expression` | The expression to negate | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Use NOT operation as logical-query operator + +This query retrieves stores where the number of full-time staff isn't equal to 5 using the `$not` operator with $eq. It returns only the `name` and `staff` fields for up to two such matching documents. + +```javascript + db.stores.find({ + "staff.totalStaff.fullTime": { + $not: { + $eq: 5 + } + } + }, { + "name": 1, + "staff": 1 + }).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "staff": { + "totalStaff": { + "fullTime": 9, + "partTime": 18 + } + } + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "name": "Lakeshore Retail | Home Decor Hub - Franciscoton", + "staff": { + "totalStaff": { + "fullTime": 7, + "partTime": 6 + } + } + } +] +``` + +### Example 2: Use NOT operator as boolean-expression to identify stores that aren't high-volume + +This query retrieves stores that don't have high sales volume (not greater than 50,000). + +```javascript +db.stores.aggregate([ + { + $project: { + name: 1, + totalSales: "$sales.salesByCategory.totalSales", + isNotHighVolume: { + $not: { $gt: ["$sales.salesByCategory.totalSales", 50000] } + }, + storeCategory: { + $cond: [ + { $not: { $gt: ["$sales.salesByCategory.totalSales", 50000] } }, + "High Volume Store", + "Small/Medium Store" + ] + } + } + }, + { $limit: 2 } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "totalSales": [ 37978 ], + "isNotHighVolume": false, + "storeCategory": "Small/Medium Store" + }, + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "totalSales": [ 25731 ], + "isNotHighVolume": false, + "storeCategory": "Small/Medium Store" + } +] +``` diff --git a/api-reference/operators/logical-query/$or.md b/api-reference/operators/logical-query/$or.md new file mode 100644 index 0000000..182567e --- /dev/null +++ b/api-reference/operators/logical-query/$or.md @@ -0,0 +1,255 @@ +--- +title: $or +description: The $or operator joins query clauses with a logical OR and returns documents that match at least one of the specified conditions. +type: operators +category: logical-query +--- + +# $or + +The `$or` operator performs a logical OR operation on an array of expressions and retrieves documents that satisfy at least one of the specified conditions. + +## Syntax + +```javascript +{ + $or: [{ + < expression1 > + }, { + < expression2 > + }, ..., { + < expressionN > + }] +} +``` + +## Parameters + +| Parameter | Description | +|-----------|-------------| +| `expression` | An array of expressions, where at least one must be true for a document to be included | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Use OR operation as logical-query + +This query retrieves stores with more than 15 full-time staff or more than 20 part-time staff, run a query using the $or operator on both the conditions. Then, project only the name and staff fields from the stores in the result set. + +```javascript +db.stores.find( + { + $or: [ + { "staff.employeeCount.fullTime": { $gt: 15 } }, + { "staff.employeeCount.partTime": { $gt: 20 } } + ] + }, + { + "name": 1, + "staff": 1 + } +).limit(2) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "dda2a7d2-6984-40cc-bbea-4cbfbc06d8a3", + "name": "Contoso, Ltd. | Home Improvement Closet - Jaskolskiview", + "staff": { + "employeeCount": { + "fullTime": 16, + "partTime": 8 + } + } + }, + { + "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", + "name": "Fourth Coffee | Storage Solution Gallery - Port Camilla", + "staff": { + "employeeCount": { + "fullTime": 17, + "partTime": 15 + } + } + } +] +``` + +### Example 2: Use OR operator as boolean-expression to identify stores with either high sales or large staff + +This query retrieves stores that have either total sales greater than 50,000 or more than 25 total staff members. + +```javascript +db.stores.aggregate([ + { + $project: { + name: 1, + totalSales: "$sales.totalSales", + totalStaff: { + $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] + }, + qualifiesForProgram: { + $or: [ + { $gt: ["$sales.totalSales", 50000] }, + { $gt: [{ $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] }, 25] } + ] + } + } + }, + { $limit: 4 } +]) +``` + +The first four results returned by this query are: + +```json +[ + { + "_id": "905d1939-e03a-413e-a9c4-221f74055aac", + "name": "Trey Research | Home Office Depot - Lake Freeda", + "totalStaff": 31, + "qualifiesForProgram": true + }, + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", + "totalStaff": 27, + "qualifiesForProgram": true + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "name": "Lakeshore Retail | Home Decor Hub - Franciscoton", + "totalStaff": 13, + "qualifiesForProgram": false + }, + { + "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", + "name": "Contoso, Ltd. | Office Supply Deals - South Shana", + "totalStaff": 2, + "qualifiesForProgram": false + } +] +``` + +## Performance Considerations + +- Review the suggestions for finding better performance. + - Each condition in the `$or` array is evaluated independently + - Use indexes when possible for better performance + - Consider the order of conditions for optimal execution + - Use `$in` instead of `$or` for multiple equality checks on the same field + - Keep the number of `$or` conditions reasonable diff --git a/api-reference/operators/miscellaneous-query/$comment.md b/api-reference/operators/miscellaneous-query/$comment.md new file mode 100644 index 0000000..251c1ef --- /dev/null +++ b/api-reference/operators/miscellaneous-query/$comment.md @@ -0,0 +1,106 @@ +--- +title: $comment +description: The $comment operator adds a comment to a query to help identify the query in logs and profiler output. +type: operators +category: miscellaneous-query +--- + +# $comment + +The `$comment` operator adds comments to queries to help identify them in logs and profiler output. This is particularly useful for debugging and monitoring database operations. + +## Syntax + +```javascript +{ + $comment: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`string`** | A string containing the comment to be included with the query. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "location": { + "lat": 70.1272, + "lon": 69.7296 + }, + "staff": { + "totalStaff": { + "fullTime": 19, + "partTime": 20 + } + }, + "sales": { + "totalSales": 151864, + "salesByCategory": [ + { + "categoryName": "Sound Bars", + "totalSales": 2120 + }, + { + "categoryName": "Home Theater Projectors", + "totalSales": 45004 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Massive Markdown Mania", + "promotionalDates": { + "startDate": { + "Year": 2023, + "Month": 6, + "Day": 29 + }, + "endDate": { + "Year": 2023, + "Month": 7, + "Day": 9 + } + }, + "discounts": [ + { + "categoryName": "DVD Players", + "discountPercentage": 14 + } + ] + } + ] +} +``` + +### Example 1: Find stores with total sales over 100,000 and add a log comment for reference + +This query retrieves stores with total sales greater than 100,000 and includes a comment for easy identification in logs. + +```javascript +db.stores.find( + { "sales.totalSales": { $gt: 100000 } }, + { name: 1, "sales.totalSales": 1 } +).comment("Query to find high-performing stores") +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "sales": { + "totalSales": 151864 + } + } +] +``` diff --git a/api-reference/operators/miscellaneous-query/$natural.md b/api-reference/operators/miscellaneous-query/$natural.md new file mode 100644 index 0000000..1002021 --- /dev/null +++ b/api-reference/operators/miscellaneous-query/$natural.md @@ -0,0 +1,144 @@ +--- +title: $natural +description: The $natural operator forces the query to use the natural order of documents in a collection, providing control over document ordering and retrieval. +type: operators +category: miscellaneous-query +--- + +# $natural + +The `$natural` operator forces the query to use the natural order of documents in a collection. It can be used in sorting operations to retrieve documents in the order they were inserted or in reverse order. This operator is useful when you need predictable ordering without relying on indexed fields. + +## Syntax + +```javascript +{ + $natural: <1 | -1> +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`1`** | Sort in forward natural order (insertion order). | +| **`-1`** | Sort in reverse natural order (reverse insertion order). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "location": { + "lat": 60.7954, + "lon": -142.0012 + }, + "staff": { + "totalStaff": { + "fullTime": 18, + "partTime": 17 + } + }, + "sales": { + "totalSales": 37701, + "salesByCategory": [ + { + "categoryName": "Mattress Toppers", + "totalSales": 37701 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Price Drop Palooza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Bath Accessories", + "discountPercentage": 18 + } + ] + } + ] +} +``` + +### Example 1: Basic Natural Order Sorting + +This query retrieves all stores in the order they were inserted into the collection. + +```javascript +db.stores.find({}).sort({ + $natural: 1 +}) +``` + +### Example 2: Reverse Natural Order + +This query returns all stores in reverse insertion order, with the most recently added documents appearing first. + +```javascript +db.stores.find({}).sort({ + $natural: -1 +}) +``` + +### Example 3: Natural Order with Filtering + +This query filters stores with total sales greater than 50,000 and returns them in natural insertion order. + +```javascript +db.stores.find({ + "sales.totalSales": { + $gt: 50000 + } +}).sort({ + $natural: 1 +}) +``` + +### Example 4: Natural Order with Projection + +This query returns only the store name, total sales, and location coordinates in natural insertion order. + +```javascript +db.stores.find({}, { + name: 1, + "sales.totalSales": 1, + "location.lat": 1, + "location.lon": 1 +}).sort({ $natural: 1 }) +``` + +### Example 5: Natural Order with Limit + +This query returns the first three stores in their natural insertion order. + +```javascript +db.stores.find({}).sort({ + $natural: 1 +}).limit(3) +``` + +## Use Cases + +The `$natural` operator is useful in the following scenarios: + +- Audit trails: When you need to process documents in the order, they were created +- Chronological processing: For time-sensitive data where insertion order matters +- Batch processing: When processing documents in predictable order without indexes +- Debugging: To understand the natural storage order of documents in a collection diff --git a/api-reference/operators/miscellaneous-query/$rand.md b/api-reference/operators/miscellaneous-query/$rand.md new file mode 100644 index 0000000..71905f7 --- /dev/null +++ b/api-reference/operators/miscellaneous-query/$rand.md @@ -0,0 +1,172 @@ +--- +title: $rand +description: The $rand operator generates a random float value between 0 and 1. +type: operators +category: miscellaneous-query +--- + +# $rand + +The `$rand` operator generates a random float value between 0 and 1. This is useful for random sampling of documents or creating random values in aggregation pipelines. + +## Syntax + +```javascript +{ + $rand: {} +} +``` + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Add a random value + +This query adds a random value to each store document. + +```javascript +db.stores.aggregate([ + { + $project: { + name: 1, + randomValue: { $rand: {} }, + "sales.totalSales": 1 + } + }, + { $limit: 2 } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "randomValue": 0.7645893472947384, + "sales": { + "totalSales": 37701 + } + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "randomValue": 0.23456789012345678, + "sales": { + "totalSales": 151864 + } + } +] +``` diff --git a/api-reference/operators/miscellaneous/$getfield.md b/api-reference/operators/miscellaneous/$getfield.md new file mode 100644 index 0000000..d418dd3 --- /dev/null +++ b/api-reference/operators/miscellaneous/$getfield.md @@ -0,0 +1,214 @@ +--- +title: $getField +description: The $getField operator allows retrieving the value of a specified field from a document. +type: operators +category: miscellaneous +--- + +# $getField + +The `$getField` operator is used to retrieve the value of a specified field from a document. It's useful when working with dynamic field names or when you need to access fields programmatically within aggregation pipelines. + +## Syntax + +```javascript +{ + $getField: { + field: , + input: + } +} +``` + +Or the shorthand syntax: + +```javascript +{ + $getField: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | A string representing the name of the field to retrieve. | +| **`input`** | The document from which the field is retrieved. If not specified, defaults to the current document (`$$ROOT`). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic field retrieval + +Retrieve the total sales value using `$getField`: + +```javascript +db.stores.aggregate([ + { $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} }, + { + $project: { + name: 1, + totalSalesValue: { + $getField: { + field: "totalSales", + input: "$sales" + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "totalSalesValue": 37701 + } +] +``` + +### Example 2: Shorthand syntax + +Use the shorthand syntax to retrieve the store name: + +```javascript +db.stores.aggregate([ + { $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} }, + { + $project: { + storeName: { $getField: "name" }, + storeLocation: { $getField: "location" } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "storeName": "First Up Consultants | Bed and Bath Center - South Amir", + "storeLocation": { + "lat": 60.7954, + "lon": -142.0012 + } + } +] +``` diff --git a/api-reference/operators/miscellaneous/$samplerate.md b/api-reference/operators/miscellaneous/$samplerate.md new file mode 100644 index 0000000..9d93d7e --- /dev/null +++ b/api-reference/operators/miscellaneous/$samplerate.md @@ -0,0 +1,184 @@ +--- +title: $sampleRate +description: The $sampleRate operator randomly samples documents from a collection based on a specified probability rate, useful for statistical analysis and testing. +type: operators +category: miscellaneous +--- + +# $sampleRate + +The `$sampleRate` operator randomly samples documents from a collection based on a specified probability rate. This operator is useful for statistical analysis, testing with subset data, and performance optimization when working with large datasets where you need a representative sample. + +## Syntax + +```javascript +{ + $match: { + $sampleRate: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`number`** | A floating-point number between 0 and 1 representing the probability that a document will be included in the sample. For example, 0.33 means approximately 33% of documents are sampled. + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic random sampling + +This query returns one-third of all documents in the stores collection, selected randomly. + +```javascript +db.stores.aggregate([{ + $match: { + $sampleRate: 0.33 + } +}]) +``` + +### Example 2: Sampling with more filters + +This query first filters stores with sales above 50,000, then randomly samples 50% of those matching documents. + +```javascript +db.stores.aggregate([ + { $match: { + "sales.totalSales": { $gt: 50000 }, + $sampleRate: 0.5 + }} +]) +``` + +### Example 3: Sampling for statistical analysis + +This query samples 25% of stores and calculates statistical measures on the sampled data. + +```javascript +db.stores.aggregate([ + { $match: { $sampleRate: 0.25 } }, + { $group: { + _id: null, + averageSales: { $avg: "$sales.totalSales" }, + totalStores: { $sum: 1 }, + maxSales: { $max: "$sales.totalSales" }, + minSales: { $min: "$sales.totalSales" } + }} +]) +``` + +The $sampleRate operator is valuable for statistical analysis and data exploration when working with large datasets where processing all documents would be computationally expensive. It efficiently creates representative samples for performance testing, quality assurance validation, and machine learning dataset generation. The operator is ideal for approximate reporting scenarios where statistical accuracy is acceptable and processing speed is prioritized over exact precision. diff --git a/api-reference/operators/object-expression/$mergeobjects.md b/api-reference/operators/object-expression/$mergeobjects.md new file mode 100644 index 0000000..0a45127 --- /dev/null +++ b/api-reference/operators/object-expression/$mergeobjects.md @@ -0,0 +1,198 @@ +--- +title: $mergeObjects +description: The $mergeObjects operator merges multiple documents into a single document +type: operators +category: object-expression +--- + +# $mergeObjects + +The `$mergeObjects` operator combines multiple documents into a single document. The mergeObjects operation is used in aggregation pipelines to merge fields from different documents or add one or more fields to an existing document. The operator overwrites fields in the target document with fields from the source document when conflicts occur. + +## Syntax + +```javascript +{ + $mergeObjects: [ < document1 > , < document2 > , ...] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`document1, document2`** | The documents to be merged. The documents can be specified as field paths, subdocuments, or constants. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Merging documents as an accumulator to group documents by the sales subdocument + +The query merges all sales subdocuments per city for a specific company. + +```javascript +db.stores.aggregate([ + { + $match: { + company: "Fourth Coffee" + } + }, + { + $group: { + _id: "$city", + mergedSales: { + $mergeObjects: "$sales" + } + } + }, + { + $limit: 2 // returns only the first 3 grouped cities + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "Jalonborough", + "mergedSales": { + "totalSales": 45747, + "salesByCategory": [ + { + "categoryName": "Bucket Bags", + "totalSales": 45747 + } + ] + } + }, + { + "_id": "Port Vladimir", + "mergedSales": { + "totalSales": 32000, + "salesByCategory": [ + { + "categoryName": "DJ Speakers", + "totalSales": 24989 + }, + { + "categoryName": "DJ Cables", + "totalSales": 7011 + } + ] + } + } +] +``` diff --git a/api-reference/operators/object-expression/$objectToArray.md b/api-reference/operators/object-expression/$objectToArray.md new file mode 100644 index 0000000..68e91a2 --- /dev/null +++ b/api-reference/operators/object-expression/$objectToArray.md @@ -0,0 +1,243 @@ +--- +title: $objectToArray +description: The objectToArray command is used to transform a document (object) into an array of key-value pairs. +type: operators +category: object-expression +--- + +# $objectToArray + +The `$objectToArray` operator is used to transform a document (object) into an array of key-value pairs. Each key-value pair in the resulting array is represented as a document with `k` and `v` fields. This operator is useful when you need to manipulate or analyze the structure of documents within your collections. + +## Syntax + +```javascript +{ + $objectToArray: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The document (object) to be transformed into an array of key-value pairs. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Transforming the `location` object + +This query transforms the `location` object into an array of key-value pairs. + +```javascript +db.stores.aggregate([ + { + $project: { + locationArray: { $objectToArray: "$location" } + } + }, + { + $limit: 2 // Limit output to first 5 documents + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "locationArray": [ + { + "k": "lat", + "v": -74.0427 + }, + { + "k": "lon", + "v": 160.8154 + } + ] + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "locationArray": [ + { + "k": "lat", + "v": 61.3945 + }, + { + "k": "lon", + "v": -3.6196 + } + ] + } +] +``` + +### Example 2: Transforming the `salesByCategory` array + +To transform the `salesByCategory` array, first unwind the array and then apply the `$objectToArray` operator. + +```javascript +db.stores.aggregate([ + { $unwind: "$sales.salesByCategory" }, + { + $project: { + salesByCategoryArray: { $objectToArray: "$sales.salesByCategory" } + } + }, + { + $limit: 2 + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", + "salesByCategoryArray": [ + { + "k": "categoryName", + "v": "Stockings" + }, + { + "k": "totalSales", + "v": 25731 + } + ] + }, + { + "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", + "salesByCategoryArray": [ + { + "k": "categoryName", + "v": "Lamps" + }, + { + "k": "totalSales", + "v": 19880 + } + ] + } +] +``` + +Converting subdocuments to key-value pairs is often used when you want to dynamically process field names, especially when: +- Building generic pipelines. +- Mapping field names into key-value structures for flexible transformations or further processing. diff --git a/api-reference/operators/object-expression/$setField.md b/api-reference/operators/object-expression/$setField.md new file mode 100644 index 0000000..bc53e0b --- /dev/null +++ b/api-reference/operators/object-expression/$setField.md @@ -0,0 +1,209 @@ +--- +title: $setField +description: The setField command is used to add, update, or remove fields in embedded documents. +type: operators +category: object-expression +--- + +# $setField + +The `$setField` operator is used to add, update, or remove fields in embedded documents. The operator allows for precise manipulation of document fields, which makes it useful for tasks such as updating nested fields, restructuring documents, or even removing fields entirely. + +## Syntax + +```javascript +{ + $setField: { + field: , + input: , + value: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **``** | The document (object) to be transformed into an array of key-value pairs. | +| **``** | The document or field being processed. | +| **``** | The new value to assign to the field. If `value` is `null`, the field is removed.| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Updating a nested field + +This query performs a conditional update on nested discount values inside promotion events for the document matching a specific `_id`. + +```javascript +db.stores.updateOne( + { "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4" }, + [ + { + $set: { + "store.promotionEvents": { + $map: { + input: "$store.promotionEvents", + as: "event", + in: { + $setField: { + field: "discounts", + input: "$$event", + value: { + $map: { + input: "$$event.discounts", + as: "discount", + in: { + $cond: { + if: { $eq: ["$$discount.categoryName", "Laptops"] }, + then: { + categoryName: "$$discount.categoryName", + discountPercentage: 18 + }, + else: "$$discount" + } + } + } + } + } + } + } + } + } + } + ] +) +``` + +### Example 2: Removing a field + +This query removes the `totalStaff` field from the `staff` object. + +```javascript +db.collection.updateOne( + { "store.storeId": "12345" }, + [{ + $set: { + "store.staff": { + $setField: { + field: "totalStaff", + input: "$store.staff", + value: null + } + } + } + }] +) +``` diff --git a/api-reference/operators/projection/$meta.md b/api-reference/operators/projection/$meta.md new file mode 100644 index 0000000..c2941d4 --- /dev/null +++ b/api-reference/operators/projection/$meta.md @@ -0,0 +1,158 @@ +--- +title: $meta +description: The $meta operator returns a calculated metadata column with returned dataset. +type: operators +category: projection +--- + +# $meta + +The `$meta` projection operator is used to include metadata in the results of a query. It's useful for including metadata such as text search scores or other computed values in the output documents. + +## Syntax + +The syntax for using the `$meta` projection operator is as follows: + +```javascript +db.collection.find({ + $text: { + $search: < string > + } +}, { + field: { + $meta: < metaDataKeyword > + } +}) +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`field`** | The name of the field in the output documents where the metadata gets included. | +| **`metaDataKeyword`** | The type of metadata to include common keywords like `textScore` for text search scores. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "34f462fe-5085-4a77-a3de-53f4117466bd", + "name": "Wide World Importers", + "location": { + "lat": -63.5435, + "lon": 77.7226 + }, + "staff": { + "totalStaff": { + "fullTime": 16, + "partTime": 16 + } + }, + "sales": { + "totalSales": 41481, + "salesByCategory": [ + { + "categoryName": "Holiday Tableware", + "totalSales": 41481 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Crazy Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2023, + "Month": 11, + "Day": 13 + }, + "endDate": { + "Year": 2023, + "Month": 11, + "Day": 22 + } + }, + "discounts": [ + { + "categoryName": "Gift Boxes", + "discountPercentage": 9 + }, + { + "categoryName": "Holiday Tableware", + "discountPercentage": 24 + } + ] + }, + { + "eventName": "Incredible Savings Showcase", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 5, + "Day": 11 + }, + "endDate": { + "Year": 2024, + "Month": 5, + "Day": 20 + } + }, + "discounts": [ + { + "categoryName": "Ribbons", + "discountPercentage": 15 + }, + { + "categoryName": "Gift Bags", + "discountPercentage": 25 + } + ] + } + ], + "tag": [ + "#ShopLocal", + "#FashionStore", + "#SeasonalSale", + "#FreeShipping", + "#MembershipDeals" + ] +} + +``` + +### Example 1: Including text search scores + +To include the text search score in the results of a text search query. + +```javascript +db.stores.createIndex({ "name": "text"}); + +db.stores.find( + { $text: { $search: "Equipment Furniture Finds" } }, + { _id: 1, name: 1, score: { $meta: "textScore" } } +).sort({ score: { $meta: "textScore" } }).limit(2) + +``` + +The first two results returned by this query are: + +```json +[ + { + _id: 'cf1448e9-5493-49b5-95da-ab8a105b5240', + name: 'Tailwind Traders | Camera Market - Wolfmouth', + score: 4 + }, + { + _id: '4fd389af-4693-4c02-93cf-0d80ae8ace07', + name: 'Wide World Importers | Camera Collection - South Cordelia', + score: 4 + } +] +``` + +## Limitation + +- If no index is used, the { $meta: "indexKey" } doesn't return anything. diff --git a/api-reference/operators/set-expression/$allelementstrue.md b/api-reference/operators/set-expression/$allelementstrue.md new file mode 100644 index 0000000..7f0e802 --- /dev/null +++ b/api-reference/operators/set-expression/$allelementstrue.md @@ -0,0 +1,175 @@ +--- +title: $allElementsTrue +description: The $allElementsTrue operator returns true if all elements in an array evaluate to true. +type: operators +category: set-expression +--- + +# $allElementsTrue + +The `$allElementsTrue` operator evaluates an array as a set. It returns `true` if no element in the array has a value of `false` or equivalent to `false` (like `null`, `0`, or `undefined`). If any element evaluates to a value of `false` or the equivalent, the operator returns `false`. + +## Syntax + +```javascript +{ + $allElementsTrue: [ ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| `array` | An array of expressions to evaluate. If the array is empty, `$allElementsTrue` returns `true`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Determine if all the discount percentages are higher than zero + +This query determines if all the discount percentages in each promotion event are greater than zero. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} }, + { $unwind: "$promotionEvents" }, + { + $project: { + allDiscountsValid: { + $allElementsTrue: [ + { + $map: { + input: "$promotionEvents.discounts.discountPercentage", + as: "discount", + in: { $gt: ["$$discount", 0] } + } + } + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "allDiscountsValid": true + } +] +``` diff --git a/api-reference/operators/set-expression/$anyelementtrue.md b/api-reference/operators/set-expression/$anyelementtrue.md new file mode 100644 index 0000000..c072b76 --- /dev/null +++ b/api-reference/operators/set-expression/$anyelementtrue.md @@ -0,0 +1,254 @@ +--- +title: $anyElementTrue +description: The $anyElementTrue operator returns true if any element in an array evaluates to a value of true. +type: operators +category: set-expression +--- + +# $anyElementTrue + +The `$anyElementTrue` operator evaluates an array as a set and returns `true` if any element in the array is `true` (or equivalent to `true`). If all the elements evaluate to a value of `false`, `null`, `0`, or `undefined`, the operator returns `false`. + +## Syntax + +```javascript +{ + $anyElementTrue: [ ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| `array` | An array of expressions to evaluate. If the array is empty, `$anyElementTrue` returns `false`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Determine if any sales category exceeds a target + +This query determines if any sales category exceeds a specified target. In this case, the target is 40,000 in sales. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + salesByCategory: "$sales.salesByCategory", + hasHighPerformingCategory: { + $anyElementTrue: [ + { + $map: { + input: "$sales.salesByCategory", + as: "category", + in: { $gt: ["$$category.totalSales", 40000] } + } + } + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "salesByCategory": [ + { + "categoryName": "Sound Bars", + "totalSales": 2120, + "lastUpdated": "2025-06-11T11:10:34.414Z" + }, + null, + { + "categoryName": "Game Controllers", + "totalSales": 43522 + }, + { + "categoryName": "Remote Controls", + "totalSales": 28946 + }, + { + "categoryName": "VR Games", + "totalSales": 32272 + } + ], + "hasHighPerformingCategory": true + } +] +``` + +### Example 2: Determine if any promotion event has high discounts + +This query determines if any promotion event offers discounts over 20%. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { $unwind: "$promotionEvents" }, + { + $project: { + eventName: "$promotionEvents.eventName", + hasHighDiscount: { + $anyElementTrue: [ + { + $map: { + input: "$promotionEvents.discounts", + as: "discount", + in: { $gte: ["$$discount.discountPercentage", 20] } + } + } + ] + } + } + } +]) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Massive Markdown Mania", + "hasHighDiscount": true + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Fantastic Deal Days", + "hasHighDiscount": true + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Discount Delight Days", + "hasHighDiscount": true + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Super Sale Spectacular", + "hasHighDiscount": true + }, + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "eventName": "Grand Deal Days", + "hasHighDiscount": true + } +] +``` diff --git a/api-reference/operators/set-expression/$setdifference.md b/api-reference/operators/set-expression/$setdifference.md new file mode 100644 index 0000000..2d62f0f --- /dev/null +++ b/api-reference/operators/set-expression/$setdifference.md @@ -0,0 +1,256 @@ +--- +title: $setDifference +description: The $setDifference operator returns a set with elements that exist in one set but not in a second set. +type: operators +category: set-expression +--- + +# $setDifference + +The `$setDifference` operator returns a set that includes elements that exist in one set but not in another set. It treats arrays as sets and ignores duplicate values and element order. + +## Syntax + +```javascript +{ + $setDifference: [ , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| `array1` | The first array to compare. Elements unique to this array are returned. | +| `array2` | The second array to compare against the first array. Elements that exist in both arrays are excluded from the result. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Find categories of products for sale but not discounted + +This query retrieves product categories that include sales data but no discounts. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + soldCategories: "$sales.salesByCategory.categoryName", + discountedCategories: { + $reduce: { + input: "$promotionEvents", + initialValue: [], + in: { + $concatArrays: ["$$value", "$$this.discounts.categoryName"] + } + } + } + } + }, + { + $project: { + name: 1, + soldCategories: 1, + discountedCategories: 1, + categoriesWithoutDiscounts: { + $setDifference: ["$soldCategories", "$discountedCategories"] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "soldCategories": [ + "Sound Bars", + "Game Controllers", + "Remote Controls", + "VR Games" + ], + "discountedCategories": [ + "DVD Players", + "Projector Lamps", + "Media Players", + "Blu-ray Players", + "Home Theater Systems", + "Televisions" + ], + "categoriesWithoutDiscounts": [ + "Sound Bars", + "Home Theater Projectors", + "Game Controllers", + "Remote Controls", + "VR Games" + ] + } +] +``` + +### Example 2: Compare staff distribution types + +This query finds the difference between two hypothetical staff requirement lists. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + requiredSkills: ["Sales", "Customer Service", "Technical Support", "Inventory Management"], + availableSkills: ["Sales", "Customer Service", "Marketing", "Administration"], + missingSkills: { + $setDifference: [ + ["Sales", "Customer Service", "Technical Support", "Inventory Management"], + ["Sales", "Customer Service", "Marketing", "Administration"] + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "requiredSkills": [ + "Sales", + "Customer Service", + "Technical Support", + "Inventory Management" + ], + "availableSkills": [ + "Sales", + "Customer Service", + "Marketing", + "Administration" + ], + "missingSkills": [ + "Technical Support", + "Inventory Management" + ] + } +] +``` diff --git a/api-reference/operators/set-expression/$setequals.md b/api-reference/operators/set-expression/$setequals.md new file mode 100644 index 0000000..c2a0047 --- /dev/null +++ b/api-reference/operators/set-expression/$setequals.md @@ -0,0 +1,269 @@ +--- +title: $setEquals +description: The $setEquals operator returns true if two sets have the same distinct elements. +type: operators +category: set-expression +--- + +# $setEquals + +The `$setEquals` operator returns `true` if two sets have the same distinct elements, regardless of order or duplicates. It treats arrays as sets and ignores duplicate values and element order. + +## Syntax + +```javascript +{ + $setEquals: [ , , ... ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| `array1, array2, ...` | Arrays to compare for equality. You can specify two or more arrays. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Compare discount categories between events + +This query determines if two promotion events offer discounts on the same categories. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "26afb024-53c7-4e94-988c-5eede72277d5"} }, + { + $project: { + name: 1, + event1Categories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }, + event2Categories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 1] }, + sameDiscountCategories: { + $setEquals: [ + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }, + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 1] } + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "event1Categories": [ + "Condenser Microphones", + "Dynamic Microphones" + ], + "event2Categories": [ + "Streaming Microphones", + "Microphone Stands" + ], + "sameDiscountCategories": false + } +] +``` + +### Example 2: Compare staff requirements + +This query determines if two stores have the same staff structure requirements. + +```javascript +db.stores.aggregate([ + { $match: {"_id": { $in: ["26afb024-53c7-4e94-988c-5eede72277d5", "f2a8c190-28e4-4e14-9d8b-0256e53dca66"] }} }, + { + $group: { + _id: null, + stores: { $push: { _id: "$_id", name: "$name" }} + } + }, + { + $project: { + store1: { $arrayElemAt: ["$stores", 0] }, + store2: { $arrayElemAt: ["$stores", 1] }, + staffTypes1: ["fullTime", "partTime"], + staffTypes2: ["fullTime", "partTime"], + sameStaffStructure: { + $setEquals: [ + ["fullTime", "partTime"], + ["fullTime", "partTime"] + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": null, + "store1": { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland" + }, + "store2": { + "_id": "f2a8c190-28e4-4e14-9d8b-0256e53dca66", + "name": "Fabrikam, Inc. | Car Accessory Outlet - West Adele" + }, + "staffTypes1": ["fullTime", "partTime"], + "staffTypes2": ["fullTime", "partTime"], + "sameStaffStructure": true + } +] +``` + +### Example 3: Compare sets with duplicates + +This query uses the `$setEquals` operator to ignore duplicates and order. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "26afb024-53c7-4e94-988c-5eede72277d5"} }, + { + $project: { + name: 1, + array1: ["Microphones", "Stands", "Microphones", "Accessories"], + array2: ["Stands", "Accessories", "Microphones"], + arraysEqual: { + $setEquals: [ + ["Microphones", "Stands", "Microphones", "Accessories"], + ["Stands", "Accessories", "Microphones"] + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "array1": ["Microphones", "Stands", "Microphones", "Accessories"], + "array2": ["Stands", "Accessories", "Microphones"], + "arraysEqual": true + } +] +``` diff --git a/api-reference/operators/set-expression/$setintersection.md b/api-reference/operators/set-expression/$setintersection.md new file mode 100644 index 0000000..8c78074 --- /dev/null +++ b/api-reference/operators/set-expression/$setintersection.md @@ -0,0 +1,253 @@ +--- +title: $setIntersection +description: The $setIntersection operator returns the common elements that appear in all input arrays. +type: operators +category: set-expression +--- + +# $setIntersection + +The `$setIntersection` operator returns an array that contains elements that appear in all of the input arrays. It treats arrays as sets, which means that it removes duplicates and ignores the order of elements. + +## Syntax + +```javascript +{ + $setIntersection: [ , , ... ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| `, , ...` | Two or more arrays to find the intersection of. Each array is treated as a set. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "location": { + "lat": 70.1272, + "lon": 69.7296 + }, + "staff": { + "totalStaff": { + "fullTime": 19, + "partTime": 20 + } + }, + "sales": { + "totalSales": 151864, + "salesByCategory": [ + { + "categoryName": "Sound Bars", + "totalSales": 2120 + }, + { + "categoryName": "Home Theater Projectors", + "totalSales": 45004 + }, + { + "categoryName": "Game Controllers", + "totalSales": 43522 + }, + { + "categoryName": "Remote Controls", + "totalSales": 28946 + }, + { + "categoryName": "VR Games", + "totalSales": 32272 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Massive Markdown Mania", + "promotionalDates": { + "startDate": { + "Year": 2023, + "Month": 6, + "Day": 29 + }, + "endDate": { + "Year": 2023, + "Month": 7, + "Day": 9 + } + }, + "discounts": [ + { + "categoryName": "DVD Players", + "discountPercentage": 14 + }, + { + "categoryName": "Projector Lamps", + "discountPercentage": 6 + }, + { + "categoryName": "Media Players", + "discountPercentage": 21 + }, + { + "categoryName": "Blu-ray Players", + "discountPercentage": 21 + }, + { + "categoryName": "Home Theater Systems", + "discountPercentage": 5 + }, + { + "categoryName": "Televisions", + "discountPercentage": 22 + } + ] + }, + { + "eventName": "Discount Delight Days", + "promotionalDates": { + "startDate": { + "Year": 2023, + "Month": 12, + "Day": 26 + }, + "endDate": { + "Year": 2024, + "Month": 1, + "Day": 5 + } + }, + "discounts": [ + { + "categoryName": "Game Controllers", + "discountPercentage": 22 + }, + { + "categoryName": "Home Theater Projectors", + "discountPercentage": 23 + }, + { + "categoryName": "Sound Bars", + "discountPercentage": 10 + }, + { + "categoryName": "Media Players", + "discountPercentage": 10 + }, + { + "categoryName": "Televisions", + "discountPercentage": 9 + }, + { + "categoryName": "Projector Lamps", + "discountPercentage": 24 + } + ] + } + ] +} +``` + +### Example 1: Find common categories between sales and promotions + +This query determines which product categories appear in a store's sales data and promotion discounts. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + salesCategories: "$sales.salesByCategory.categoryName", + firstPromotionCategories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }, + secondPromotionCategories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 1] }, + commonSalesAndFirstPromotion: { + $setIntersection: [ + "$sales.salesByCategory.categoryName", + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] } + ] + }, + commonSalesAndSecondPromotion: { + $setIntersection: [ + "$sales.salesByCategory.categoryName", + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 1] } + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "salesCategories": [ + "Sound Bars", + "Game Controllers", + "Remote Controls", + "VR Games" + ], + "firstPromotionCategories": [ + "DVD Players", + "Projector Lamps", + "Media Players", + "Blu-ray Players", + "Home Theater Systems", + "Televisions" + ], + "secondPromotionCategories": [ + "TV Mounts", + "Game Accessories", + "Portable Projectors", + "Projector Screens", + "Blu-ray Players", + "DVD Players" + ], + "commonSalesAndFirstPromotion": [], + "commonSalesAndSecondPromotion": [] + } +] +``` + +### Example 2: Find common categories across multiple promotion events + +This query fetches categories that appear in multiple promotion events. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + commonAcrossPromotions: { + $setIntersection: [ + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }, + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 1] }, + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 2] } + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74", + "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury", + "commonAcrossPromotions": [] + } +] +``` diff --git a/api-reference/operators/set-expression/$setissubset.md b/api-reference/operators/set-expression/$setissubset.md new file mode 100644 index 0000000..73aeb7d --- /dev/null +++ b/api-reference/operators/set-expression/$setissubset.md @@ -0,0 +1,171 @@ +--- +title: $setIsSubset +description: The $setIsSubset operator determines if one array is a subset of a second array. +type: operators +category: set-expression +--- + +# $setIsSubset + +The `$setIsSubset` operator returns a Boolean value that indicates if one array is a subset of a second array. It treats arrays as sets, which means it ignores duplicates and element order. It returns `true` if all the elements in the first array exist in the second array. Otherwise, it returns `false`. + +## Syntax + +```javascript +{ + $setIsSubset: [ , ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| `` | The array to check to see if it's a subset of ``. | +| `` | The array to check against. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "location": { + "lat": 60.7954, + "lon": -142.0012 + }, + "staff": { + "totalStaff": { + "fullTime": 18, + "partTime": 17 + } + }, + "sales": { + "totalSales": 37701, + "salesByCategory": [ + { + "categoryName": "Mattress Toppers", + "totalSales": 37701 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Price Drop Palooza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Bath Accessories", + "discountPercentage": 18 + }, + { + "categoryName": "Pillow Top Mattresses", + "discountPercentage": 17 + }, + { + "categoryName": "Bathroom Scales", + "discountPercentage": 9 + }, + { + "categoryName": "Towels", + "discountPercentage": 5 + }, + { + "categoryName": "Bathrobes", + "discountPercentage": 5 + }, + { + "categoryName": "Mattress Toppers", + "discountPercentage": 6 + }, + { + "categoryName": "Hand Towels", + "discountPercentage": 9 + }, + { + "categoryName": "Shower Heads", + "discountPercentage": 5 + }, + { + "categoryName": "Bedspreads", + "discountPercentage": 19 + }, + { + "categoryName": "Bath Mats", + "discountPercentage": 21 + } + ] + } + ] +} +``` + +### Example 1: Determine if sales categories are a subset of promotion categories + +This query determines if all of a store's categories are included in their promotion discounts, and vice versa. This query returns categories included under both the sales and promotion brackets. It confirms that the `sales` value is a subset of a particular promotion category (but doesn't do the reverse). + +```javascript +db.stores.aggregate([ + { $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} }, + { + $project: { + name: 1, + salesCategories: "$sales.salesByCategory.categoryName", + promotionCategories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }, + salesAreSubsetOfPromotions: { + $setIsSubset: [ + "$sales.salesByCategory.categoryName", + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] } + ] + }, + promotionsAreSubsetOfSales: { + $setIsSubset: [ + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }, + "$sales.salesByCategory.categoryName" + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "salesCategories": [ + "Mattress Toppers" + ], + "promotionCategories": [ + "Bath Accessories", + "Pillow Top Mattresses", + "Bathroom Scales", + "Towels", + "Bathrobes", + "Mattress Toppers", + "Hand Towels", + "Shower Heads", + "Bedspreads", + "Bath Mats" + ], + "salesAreSubsetOfPromotions": true, + "promotionsAreSubsetOfSales": false + } +] +``` diff --git a/api-reference/operators/set-expression/$setunion.md b/api-reference/operators/set-expression/$setunion.md new file mode 100644 index 0000000..c110110 --- /dev/null +++ b/api-reference/operators/set-expression/$setunion.md @@ -0,0 +1,197 @@ +--- +title: $setUnion +description: The $setUnion operator returns an array that contains all the unique elements from the input arrays. +type: operators +category: set-expression +--- + +# $setUnion + +The `$setUnion` operator returns an array that contains all the unique elements from the input arrays. It treats arrays as sets, removes duplicates, and ignores element order. The result contains each unique element only once, regardless of how many times it appears across the input arrays. + +## Syntax + +```javascript +{ + $setUnion: [ , , ... ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| `, , ...` | Two or more arrays to combine. Each array is treated as a set, and duplicates are removed from the final result. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "location": { + "lat": -29.1866, + "lon": -112.7858 + }, + "staff": { + "totalStaff": { + "fullTime": 14, + "partTime": 8 + } + }, + "sales": { + "totalSales": 83865, + "salesByCategory": [ + { + "categoryName": "Lavalier Microphones", + "totalSales": 44174 + }, + { + "categoryName": "Wireless Microphones", + "totalSales": 39691 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Price Cut Spectacular", + "promotionalDates": { + "startDate": { + "Year": 2023, + "Month": 12, + "Day": 26 + }, + "endDate": { + "Year": 2024, + "Month": 1, + "Day": 5 + } + }, + "discounts": [ + { + "categoryName": "Condenser Microphones", + "discountPercentage": 5 + }, + { + "categoryName": "Dynamic Microphones", + "discountPercentage": 14 + } + ] + }, + { + "eventName": "Bargain Bonanza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 3, + "Day": 25 + }, + "endDate": { + "Year": 2024, + "Month": 4, + "Day": 3 + } + }, + "discounts": [ + { + "categoryName": "Streaming Microphones", + "discountPercentage": 14 + }, + { + "categoryName": "Microphone Stands", + "discountPercentage": 14 + } + ] + }, + { + "eventName": "Super Savings Extravaganza", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 6, + "Day": 30 + } + }, + "discounts": [ + { + "categoryName": "Condenser Microphones", + "discountPercentage": 7 + }, + { + "categoryName": "Microphone Stands", + "discountPercentage": 5 + } + ] + } + ] +} +``` + +### Example 1: Combine all product categories + +This query retrieves a list of all of a store's unique product categories. The list includes sales and promotion categories. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "26afb024-53c7-4e94-988c-5eede72277d5"} }, + { + $project: { + name: 1, + salesCategories: "$sales.salesByCategory.categoryName", + firstPromotionCategories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }, + secondPromotionCategories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 1] }, + thirdPromotionCategories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 2] }, + allUniqueCategories: { + $setUnion: [ + "$sales.salesByCategory.categoryName", + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }, + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 1] }, + { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 2] } + ] + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "name": "First Up Consultants | Microphone Bazaar - South Lexusland", + "salesCategories": [ + "Lavalier Microphones", + "Wireless Microphones" + ], + "firstPromotionCategories": [ + "Condenser Microphones", + "Dynamic Microphones" + ], + "secondPromotionCategories": [ + "Streaming Microphones", + "Microphone Stands" + ], + "thirdPromotionCategories": [ + "Condenser Microphones", + "Microphone Stands" + ], + "allUniqueCategories": [ + "Lavalier Microphones", + "Wireless Microphones", + "Condenser Microphones", + "Dynamic Microphones", + "Streaming Microphones", + "Microphone Stands" + ] + } +] +``` diff --git a/api-reference/operators/timestamp-expression/$tsincrement.md b/api-reference/operators/timestamp-expression/$tsincrement.md new file mode 100644 index 0000000..a0bb7ae --- /dev/null +++ b/api-reference/operators/timestamp-expression/$tsincrement.md @@ -0,0 +1,168 @@ +--- +title: $tsIncrement +description: The $tsIncrement operator extracts the increment portion from a timestamp value. +type: operators +category: timestamp-expression +--- + +# $tsIncrement + +The `$tsIncrement` operator returns the increment value from a timestamp. + +## Syntax + +```javascript +{ + $tsIncrement: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | An expression that evaluates to a timestamp. If the expression does not evaluate to a timestamp, `$tsIncrement` returns an error. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract increment from audit timestamp + +Extract the increment value from the last updated timestamp in the audit log. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} }, + { + $project: { + name: 1, + lastUpdatedIncrement: { + $tsIncrement: "$auditLog.lastUpdated" + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "lastUpdatedIncrement": Long("5") + } +] +``` diff --git a/api-reference/operators/timestamp-expression/$tssecond.md b/api-reference/operators/timestamp-expression/$tssecond.md new file mode 100644 index 0000000..843ee66 --- /dev/null +++ b/api-reference/operators/timestamp-expression/$tssecond.md @@ -0,0 +1,177 @@ +--- +title: $tsSecond +description: The $tsSecond operator extracts the seconds portion from a timestamp value. +type: operators +category: timestamp-expression +--- + +# $tsSecond + +The `$tsSecond` operator returns the seconds value from a timestamp. Timestamps consist of two parts: a time value (in seconds since epoch) and an increment value. This operator extracts the seconds portion, which represents the time since the Unix epoch (January 1, 1970, 00:00:00 UTC). + +## Syntax + +```javascript +{ + $tsSecond: +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`expression`** | An expression that evaluates to a timestamp. If the expression does not evaluate to a timestamp, `$tsSecond` returns an error. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Extract seconds from audit timestamp + +This query extracts the seconds value from the last updated timestamp in the audit log. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} }, + { + $project: { + name: 1, + lastUpdatedSeconds: { + $tsSecond: "$lastUpdated" + }, + lastUpdatedDate: { + $toDate: { + $multiply: [ + { $tsSecond: "$lastUpdated" }, + 1000 + ] + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "lastUpdatedSeconds": Long("1640995200"), + "lastUpdatedDate": ISODate("2022-01-01T00:00:00.000Z") + } +] +``` diff --git a/api-reference/operators/variable-expression/$let.md b/api-reference/operators/variable-expression/$let.md new file mode 100644 index 0000000..5b861a4 --- /dev/null +++ b/api-reference/operators/variable-expression/$let.md @@ -0,0 +1,253 @@ +--- +title: $let +description: The $let operator allows defining variables for use in a specified expression, enabling complex calculations and reducing code repetition. +type: operators +category: variable-expression +--- + +# $let + +The `$let` operator is used to define variables for use in a specified expression. It allows you to create temporary variables that can be referenced within the expression, making complex calculations more readable and preventing redundant computations. + +## Syntax + +```javascript +{ + $let: { + vars: { + : , + : , + ... + }, + in: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`vars`** | An object that defines the variables and their values. Each variable is assigned the result of an expression. | +| **`in`** | The expression that uses the variables defined in the `vars` object. Variables are referenced using `$$`. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Basic variable usage + +Calculate staff efficiency metrics using defined variables. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + staffMetrics: { + $let: { + vars: { + fullTime: "$staff.totalStaff.fullTime", + partTime: "$staff.totalStaff.partTime", + totalSales: "$sales.totalSales" + }, + in: { + totalStaff: { $add: ["$$fullTime", "$$partTime"] }, + salesPerEmployee: { $divide: ["$$totalSales", { $add: ["$$fullTime", "$$partTime"] }] }, + fullTimeRatio: { $divide: ["$$fullTime", { $add: ["$$fullTime", "$$partTime"] }] } + } + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": '40d6f4d7-50cd-4929-9a07-0a7a133c2e74', + "name": 'Proseware, Inc. | Home Entertainment Hub - East Linwoodbury', + "staffMetrics": { + "totalStaff": 39, + "salesPerEmployee": 3893.948717948718, + "fullTimeRatio": 0.5128205128205128 + } + } +] +``` + +### Example 2: Nested $let expressions + +Calculate location-based insights with nested variable definitions. + +```javascript +db.stores.aggregate([ + { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} }, + { + $project: { + name: 1, + locationInsights: { + $let: { + vars: { + lat: "$location.lat", + lon: "$location.lon" + }, + in: { + coordinates: { lat: "$$lat", lon: "$$lon" }, + hemisphere: { + $let: { + vars: { + northSouth: { $cond: [{ $gte: ["$$lat", 0] }, "North", "South"] }, + eastWest: { $cond: [{ $gte: ["$$lon", 0] }, "East", "West"] } + }, + in: { + latitudeHemisphere: "$$northSouth", + longitudeHemisphere: "$$eastWest", + quadrant: { $concat: ["$$northSouth", " ", "$$eastWest"] } + } + } + }, + distanceFromEquator: { $abs: "$$lat" }, + distanceFromPrimeMeridian: { $abs: "$$lon" } + } + } + } + } + } +]) +``` + +This query returns the following result. + +```json +[ + { + "_id": '40d6f4d7-50cd-4929-9a07-0a7a133c2e74', + "name": 'Proseware, Inc. | Home Entertainment Hub - East Linwoodbury', + "locationInsights": { + "coordinates": { "lat": 70.1272, "lon": 69.7296 }, + "hemisphere": { + "latitudeHemisphere": 'North', + "longitudeHemisphere": 'East', + "quadrant": 'North East' + }, + "distanceFromEquator": 70.1272, + "distanceFromPrimeMeridian": 69.7296 + } + } +] +``` diff --git a/api-reference/operators/window-operators/$covariancepop.md b/api-reference/operators/window-operators/$covariancepop.md new file mode 100644 index 0000000..69bd731 --- /dev/null +++ b/api-reference/operators/window-operators/$covariancepop.md @@ -0,0 +1,216 @@ +--- +title: $covariancePop +description: The $covariancePop operator returns the covariance of two numerical expressions +type: operators +category: window-operators +--- + +# $covariancePop + +The `$covariancePop` operator sorts documents on one or more fields within a partition and calculates a covariance of two numerical fields within a specified document window. + +## Syntax + +```javascript +{ + $covariancePop: [ < numericalExpression1 > , < numericalExpression2 > ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`numericalExpression1`** | The first numerical expression to use to calculate the covariance within the specified document window| +| **`numericalExpression2`** | The first numerical expression to use to calculate the covariance within the specified document window| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the covariance in sales volume + +To get the covariance in total sales for stores in the First Up Consultants company, first run a query to filter on the company name, then sort the resulting documents in ascending order of the last updated timestamp, and calculate the covariance between the first and current document in the sorted result set. + +```javascript +db.stores.aggregate( + [{ + "$match": { + "company": { + "$in": [ + "First Up Consultants" + ] + } + } + }, + { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "lastUpdated": 1 + }, + "output": { + "covariancePopForSales": { + "$covariancePop": [{ + "$hour": "$lastUpdated" + }, + "$sales.totalSales" + ], + "window": { + "documents": [ + "unbounded", + "current" + ] + } + } + } + } + }, + { + "$project": { + "company": 1, + "name": 1, + "sales.totalSales": 1, + "lastUpdated": 1, + "covariancePopForSales": 1 + } + } + ] +) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "sales": {}, + "company": "First Up Consultants", + "lastUpdated": "2025-06-11T10:48:01.291Z", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "covariancePopForSales": null + }, + { + "_id": "8e7a259b-f7d6-4ec5-a521-3bed53adc587", + "name": "First Up Consultants | Drone Stop - Lake Joana", + "sales": {}, + "company": "First Up Consultants", + "lastUpdated": { + "t": 1727827539, + "i": 1 + }, + "covariancePopForSales": null + } +] +``` diff --git a/api-reference/operators/window-operators/$covariancesamp.md b/api-reference/operators/window-operators/$covariancesamp.md new file mode 100644 index 0000000..baeb20d --- /dev/null +++ b/api-reference/operators/window-operators/$covariancesamp.md @@ -0,0 +1,229 @@ +--- +title: $covarianceSamp +description: The $covarianceSamp operator returns the covariance of a sample of two numerical expressions +type: operators +category: window-operators +--- + +# $covarianceSamp + +The `$covarianceSamp` operator sorts documents on one or more fields within a partition and calculates the covariance of a sample two numerical fields within a specified document window. + +## Syntax + +```javascript +{ + $covarianceSamp: [ < numericalExpression1 > , < numericalExpression2 > ] +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`numericalExpression1`** | The first numerical expression to use to calculate the covariance sample within the specified document window| +| **`numericalExpression2`** | The first numerical expression to use to calculate the covariance sample within the specified document window| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the covariance sample between an unbounded starting document and the current document + +To calculate the covariance sample for stores in the First Up Consultants company, first run a query to filter on the company, then sort the resulting stores in ascending order of their opening dates, and calculate the covariance of the sales of the sorted result set. + +```javascript +db.stores.aggregate( +[{ + "$match": { + "company": { + "$in": [ + "First Up Consultants" + ] + }, + "$and": [ + { + "storeOpeningDate": { + "$gt": ISODate("2024-09-01T03:06:24.180Z") + } + }, + { + "storeOpeningDate": { + "$lt": ISODate("2025-09-30T03:55:17.557Z") + } + } + ] + } + }, + { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "storeOpeningDate": 1 + }, + "output": { + "covarianceSampForSales": { + "$covarianceSamp": [ + { + "$hour": "$storeOpeningDate" + }, + "$sales.revenue" + ], + "window": { + "documents": [ + "unbounded", + "current" + ] + } + } + } + } + }, + { + "$project": { + "company": 1, + "name": 1, + "sales.revenue": 1, + "storeOpeningDate": 1, + "covarianceSampForSales": 1 + } + }] +) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "2d315043-db26-4d18-8bb7-71ba922f00a0", + "name": "First Up Consultants | Furniture Shoppe - Wymantown", + "sales": { + "revenue": 38042 + }, + "company": "First Up Consultants", + "storeOpeningDate": "2024-09-02T02:00:52.592Z", + "covarianceSampForSales": 935.0972222222222 + }, + { + "_id": "416adb8c-7d65-40e5-af88-8659c71194ce", + "name": "First Up Consultants | Picture Frame Bazaar - South Lysanneborough", + "sales": { + "revenue": 37157 + }, + "company": "First Up Consultants", + "storeOpeningDate": "2024-09-02T02:39:50.269Z", + "covarianceSampForSales": 1901.1777777777777 + } +] +``` diff --git a/api-reference/operators/window-operators/$denserank.md b/api-reference/operators/window-operators/$denserank.md new file mode 100644 index 0000000..7fcd036 --- /dev/null +++ b/api-reference/operators/window-operators/$denserank.md @@ -0,0 +1,211 @@ +--- +title: $denseRank +description: The $denseRank operator assigns and returns a positional ranking for each document within a partition based on a specified sort order +type: operators +category: window-operators +--- + +# $denseRank + +The `$denseRank` operator sorts documents on one or more fields within a partition and assigns a ranking for each document relative to other documents in the result set. + +## Syntax + +```javascript +{ + $denseRank: {} +} +``` + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Retrieve a document rank for each store + +To calculate a document rank for each store under the First Up Consultants company, first run a query to filter on the company, then sort the resulting documents in descending order of sales and assign a document rank to each document in the sorted result set. + +```javascript +db.stores.aggregate([{ + "$match": { + "company": { + "$in": ["First Up Consultants"] + } + } +}, { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "sales.totalSales": -1 + }, + "output": { + "denseRank": { + "$denseRank": {} + } + } + } +}, { + "$project": { + "company": 1, + "sales.totalSales": 1, + "denseRank": 1 + } +}]) +``` + +The first five results returned by this query are: + +```json +[ + { + "_id": "a0386810-b6f8-4b05-9d60-e536fb2b0026", + "sales": { + "revenue": 327583 + }, + "company": "First Up Consultants", + "denseRank": 1 + }, + { + "_id": "ad8af64a-d5bb-4162-9bb6-e5104126566d", + "sales": { + "revenue": 288582 + }, + "company": "First Up Consultants", + "denseRank": 2 + }, + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "sales": { + "revenue": 279183 + }, + "company": "First Up Consultants", + "denseRank": 3 + }, + { + "_id": "cd3d3782-17d1-451e-8b0f-4f10a68a8db7", + "sales": { + "revenue": 271604 + }, + "company": "First Up Consultants", + "denseRank": 4 + }, + { + "_id": "63ac4722-fc87-4526-a5e0-b5767d2807f7", + "sales": { + "revenue": 260409 + }, + "company": "First Up Consultants", + "denseRank": 5 + } +] +``` diff --git a/api-reference/operators/window-operators/$derivative.md b/api-reference/operators/window-operators/$derivative.md new file mode 100644 index 0000000..970ce74 --- /dev/null +++ b/api-reference/operators/window-operators/$derivative.md @@ -0,0 +1,211 @@ +--- +title: $derivative +description: The $derivative operator calculates the average rate of change of the value of a field within a specified window. +type: operators +category: window-operators +--- + +# $derivative + +The `$derivative` operator sorts documents on one or more fields within a partition and calculates the average rate of change of a field between the first and last documents within the window. + +## Syntax + +```javascript +{ + $derivative: { + input: < expression >, + unit: < timeWindow > + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The expression or the field to calculate the rate of range| +| **`unit`** | The time window for the rate of change| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the derivative for total sales + +To calculate the derivative of total sales for each store in the First Up Consultants company, first run a query to filter on the company, sort the resulting documents in ascending order of their last updated timestamps, and calculate the derivate (average rate of change) of total sales between the first and current document in the result set. + +```javascript +db.stores.aggregate([{ + "$match": { + "company": { + "$in": [ + "First Up Consultants" + ] + }, + "$and": [{ + "lastUpdated": { + "$gt": ISODate("2024-12-01T03:06:24.180Z") + } + }, + { + "lastUpdated": { + "$lt": ISODate("2025-12-01T03:55:17.557Z") + } + } + ] + } + }, + { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "lastUpdated": 1 + }, + "output": { + "storeAverageSales": { + "$derivative": { + "input": "$sales.totalSales", + "unit": "week" + }, + "window": { + "range": [ + -1, + 0 + ], + "unit": "week" + } + } + } + } + }, + { + "$project": { + "lastUpdated": 1, + "storeAverageSales": 1 + } + } +]) +``` + +This query returns the following result: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "lastUpdated": "2025-06-11T10:48:01.291Z", + "storeAverageSales": 21554495.708753344 + } +] +``` diff --git a/api-reference/operators/window-operators/$documentnumber.md b/api-reference/operators/window-operators/$documentnumber.md new file mode 100644 index 0000000..fc0236b --- /dev/null +++ b/api-reference/operators/window-operators/$documentnumber.md @@ -0,0 +1,195 @@ +--- +title: $documentNumber +description: The $documentNumber operator assigns and returns a position for each document within a partition based on a specified sort order +type: operators +category: window-operators +--- + +# $documentNumber + +The `$documentNumber` operator sorts documents on one or more fields within a partition and assigns a document number for each document in the result set. + +## Syntax + +```javascript +{ + $documentNumber: {} +} +``` + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Retrieve a document number by total sales + +To retrieve a document number (positional ranking) for each store under the First Up Consultants company, first run a query to filter on the company name, then sort the results in ascending order of total sales, and assign a document number to each of the documents in the sorted result set. + +```javascript +db.stores.aggregate([{ + "$match": { + "company": { + "$in": ["First Up Consultants"] + } + } +}, { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "sales.totalSales": -1 + }, + "output": { + "documentNumber": { + "$documentNumber": {} + } + } + } +}, { + "$project": { + "company": 1, + "documentNumber": 1 + } +}]) +``` + +The first 5 results returned by this query are: + +```json +[ + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "company": "First Up Consultants", + "documentNumber": 1 + }, + { + "_id": "26afb024-53c7-4e94-988c-5eede72277d5", + "company": "First Up Consultants", + "documentNumber": 2 + }, + { + "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad", + "company": "First Up Consultants", + "documentNumber": 3 + }, + { + "_id": "bfb213fa-8db8-419f-8e5b-e7096120bad2", + "company": "First Up Consultants", + "documentNumber": 4 + }, + { + "_id": "14ab145b-0819-4d22-9e02-9ae0725fcda9", + "company": "First Up Consultants", + "documentNumber": 5 + } +] +``` diff --git a/api-reference/operators/window-operators/$expmovingavg.md b/api-reference/operators/window-operators/$expmovingavg.md new file mode 100644 index 0000000..596efed --- /dev/null +++ b/api-reference/operators/window-operators/$expmovingavg.md @@ -0,0 +1,285 @@ +--- +title: $expMovingAvg +description: The $expMovingAvg operator calculates the moving average of a field based on the specified number of documents to hold the highest weight +type: operators +category: window-operators +--- + +# $expMovingAvg + +The `$expMovingAvg` operator calculates the exponential moving average of the values of a specified field. + +## Syntax + +```javascript +{ + $expMovingAvg: { + input: < field to use for calculation >, + N: < number of recent documents with the highest weight + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The field whose values are used to calculate the exponential moving average| +| **`N`** | The number of previous documents with the highest weight in calculating the exponential moving average| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the exponential moving average of total sales + +To retrieve the exponential moving average of the total sales across all stores within the First Up Consultants company, first run a query to filter on the company. Then, sort the resulting documents in ascending order of their opening date. Finally, assigned the highest weight to the two most recent documents to calculate the exponential moving average of total sales. + +```javascript +db.stores.aggregate( +[{ + "$match": { + "company": { + "$in": [ + "First Up Consultants" + ] + } + } + }, + { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "storeOpeningDate": 1 + }, + "output": { + "expMovingAvgForSales": { + "$expMovingAvg": { + "input": "$sales.totalSales", + "N": 2 + } + } + } + } + }, + { + "$project": { + "company": 1, + "name": 1, + "sales.totalSales": 1, + "storeOpeningDate": 1, + "expMovingAvgForSales": 1 + } + }]) +``` + +The firs two results returned by this query are: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "sales": { + "revenue": 37701 + }, + "company": "First Up Consultants", + "storeOpeningDate": { + "$date": 1633219200000 + }, + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "expMovingAvgForSales": 37701 + }, + { + "_id": "8e7a259b-f7d6-4ec5-a521-3bed53adc587", + "name": "First Up Consultants | Drone Stop - Lake Joana", + "sales": { + "revenue": 14329 + }, + "company": "First Up Consultants", + "storeOpeningDate": { + "$date": 1706958339311 + }, + "expMovingAvgForSales": 22119.666666666668 + } +] +``` + +### Example 2 - Calculate the exponential moving average of the total sales using the alpha parameter + +To retrieve the exponential moving average of the total sales across all stores within the First Up Consultants company, first run a query to filter on the company. Then, sort the resulting documents in ascending order of their opening date. Finally, specify a decay rate (alpha) to calculate the exponential moving average of total sales. A higher alpha value gives previous documents a lower weight in the calculation. + +```javascript +db.stores.aggregate( +[{ + "$match": { + "company": { + "$in": [ + "First Up Consultants" + ] + } + } + }, + { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "storeOpeningDate": 1 + }, + "output": { + "expMovingAvgForSales": { + "$expMovingAvg": { + "input": "$sales.totalSales", + "alpha": 0.75 + } + } + } + } + }, + { + "$project": { + "company": 1, + "name": 1, + "sales.totalSales": 1, + "storeOpeningDate": 1, + "expMovingAvgForSales": 1 + } + } +]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "sales": { + "revenue": 37701 + }, + "company": "First Up Consultants", + "storeOpeningDate": "2021-10-03T00:00:00.000Z", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "expMovingAvgForSales": 37701 + }, + { + "_id": "8e7a259b-f7d6-4ec5-a521-3bed53adc587", + "name": "First Up Consultants | Drone Stop - Lake Joana", + "sales": { + "revenue": 14329 + }, + "company": "First Up Consultants", + "storeOpeningDate": "2024-09-02T00:05:39.311Z", + "expMovingAvgForSales": 20172 + } +] +``` diff --git a/api-reference/operators/window-operators/$integral.md b/api-reference/operators/window-operators/$integral.md new file mode 100644 index 0000000..ce22443 --- /dev/null +++ b/api-reference/operators/window-operators/$integral.md @@ -0,0 +1,218 @@ +--- +title: $integral +description: The $integral operator calculates the area under a curve with the specified range of documents forming the adjacent documents for the calculation. +type: operators +category: window-operators +--- + +# $integral + +The `$integral` operator calculates the area under a curve based on the specified range of documents sorted based on a specific field. + +## Syntax + +```javascript +{ + $integral: { + input: < expression > , + unit: < time window > + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The field in the documents for the integral| +| **`unit`** | The specified time unit for the integral| + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1 - Calculate the integral of total sales + +To calculate the integral of total sales across all stores under the First Up Consultants company, first run a query to filter on the company name. Then, sort the resulting stores in ascending order of their opening dates. Lastly, calculate the integral of total sales from the first to the current document in the sorted result set. + +```javascript +db.stores.aggregate( +[{ + "$match": { + "company": { + "$in": [ + "First Up Consultants" + ] + } + } + }, + { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "storeOpeningDate": 1 + }, + "output": { + "salesIntegral": { + "$integral": { + "input": "$sales.revenue", + "unit": "hour" + }, + "window": { + "range": [ + "unbounded", + "current" + ], + "unit": "hour" + } + } + } + } + }, + { + "$project": { + "company": 1, + "name": 1, + "sales.revenue": 1, + "storeOpeningDate": 1, + "salesIntegral": 1 + } + }]) +``` + +The first two results returned by this query are: + +```json +[ + { + "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f", + "sales": { + "revenue": 37701 + }, + "company": "First Up Consultants", + "storeOpeningDate": "2021-10-03T00:00:00.000Z", + "name": "First Up Consultants | Bed and Bath Center - South Amir", + "salesIntegral": 0 + }, + { + "_id": "8e7a259b-f7d6-4ec5-a521-3bed53adc587", + "name": "First Up Consultants | Drone Stop - Lake Joana", + "sales": { + "revenue": 14329 + }, + "company": "First Up Consultants", + "storeOpeningDate": "2024-09-02T00:05:39.311Z", + "salesIntegral": 664945851.9932402 + } +] +``` diff --git a/api-reference/operators/window-operators/$linearfill.md b/api-reference/operators/window-operators/$linearfill.md new file mode 100644 index 0000000..c10d1b2 --- /dev/null +++ b/api-reference/operators/window-operators/$linearfill.md @@ -0,0 +1,194 @@ +--- +title: $linearFill +description: The $linearFill operator interpolates missing values in a sequence of documents using linear interpolation. +type: operators +category: window-operators +--- + +# $linearFill + +The `$linearFill` operator interpolates missing values in a sequence of documents. The $linearFill operator performs linear interpolation for missing data, making it useful for datasets with gaps in values, such as time-series data. + +## Syntax + +```javascript +{ + $linearFill: { + input: < expression > , + sortBy: { + < field >: < 1 or - 1 > + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The field or expression to interpolate missing values for. | +| **`sortBy`** | Specifies the field by which the data is sorted for interpolation, along with the sort order (1 for ascending, -1 for descending). | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Interpolating missing sales data + +To interpolate missing sales data, run a query to first partition the stores in the dataset by name. Then, use the $linearFill operator to interpolate the missing sales data across the stores within the partition. + +```javascript +db.stores.aggregate([{ + "$match": { + "company": { + "$in": ["First Up Consultants"] + } + } + }, + { + "$setWindowFields": { + "partitionBy": "$name", + "sortBy": { + "storeOpeningDate": 1 + }, + "output": { + "interpolatedSales": { + "$linearFill": "$sales.totalSales" + } + } + } + } +]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "0f4c48fe-c43b-4083-a856-afe6dd902077", + "name": "First Up Consultants | Appliance Bargains - Feilmouth", + "interpolatedSales": 26630 + }, + { + "_id": "c4883253-7ccd-4054-a7e0-8aeb202307b5", + "name": "First Up Consultants | Appliance Bargains - New Kari", + "interpolatedSales": 31568 + }, + { + "_id": "a159ff5c-6ec5-4ca8-9672-e8903a54dd90", + "name": "First Up Consultants | Appliance Bargains - Schadenstad", + "interpolatedSales": 59926 + } +] +``` diff --git a/api-reference/operators/window-operators/$locf.md b/api-reference/operators/window-operators/$locf.md new file mode 100644 index 0000000..397f8cf --- /dev/null +++ b/api-reference/operators/window-operators/$locf.md @@ -0,0 +1,198 @@ +--- +title: $locf +description: The $locf operator propagates the last observed non-null value forward within a partition in a windowed query. +type: operators +category: window-operators +--- + +# $locf + +The `$locf` operator propagates the last observed non-null value forward within a partition in a windowed query. The $locf operator is particularly useful in filling missing data points in time-series data or other datasets with gaps. + +## Syntax + +```javascript +{ + $locf: { + input: , + sortBy: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`input`** | The expression that resolves to the field whose value you want to propagate. | +| **`sortBy`** | A document that specifies the sort order for the partition. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Using `$locf` to fill missing time series data + +To propagate the most recent non-null value for the lastUpdated field across stores within the "First Up Consultants" company, first run a query to partition the stores within the company. Then, use the $lecf operator to propagate the last non-null value for the field for all stores within the partition. + +```javascript +db.stores.aggregate([{ + "$match": { + "company": { + "$in": ["First Up Consultants"] + } + } +}, { + "$setWindowFields": { + "partitionBy": "$name", + "sortBy": { + "sales.revenue": 1 + }, + "output": { + "lastUpdatedDate": { + "$locf": { + "lastUpdated": 1 + } + } + } + } +}, { + "$project": { + "company": 1, + "name": 1, + "lastObservedDiscount": 1 + } +}]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "0f4c48fe-c43b-4083-a856-afe6dd902077", + "name": "First Up Consultants | Appliance Bargains - Feilmouth", + "company": "First Up Consultants" + }, + { + "_id": "c4883253-7ccd-4054-a7e0-8aeb202307b5", + "name": "First Up Consultants | Appliance Bargains - New Kari", + "company": "First Up Consultants" + }, + { + "_id": "a159ff5c-6ec5-4ca8-9672-e8903a54dd90", + "name": "First Up Consultants | Appliance Bargains - Schadenstad", + "company": "First Up Consultants" + } +] +``` diff --git a/api-reference/operators/window-operators/$rank.md b/api-reference/operators/window-operators/$rank.md new file mode 100644 index 0000000..11db7c1 --- /dev/null +++ b/api-reference/operators/window-operators/$rank.md @@ -0,0 +1,207 @@ +--- +title: $rank +description: The $rank operator ranks documents within a partition based on a specified sort order. +type: operators +category: window-operators +--- + +# $rank + +The `$rank` operator assigns a rank to each document within a partition of a dataset. The rank is determined based on a specified sort order. + +## Syntax + +```javascript +{ + $setWindowFields: { + partitionBy: < expression > , + sortBy: { + < field >: < order > + }, + output: { + < outputField >: { + $rank: {} + } + } + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`partitionBy`** | Specifies the expression to group documents into partitions. If omitted, all documents are treated as a single partition. | +| **`sortBy`** | Defines the sort order for ranking. Must be specified for `$rank`. | +| **`output`** | Contains the field where the rank value is stored. | + +## Examples + +Consider this sample document from the stores collection. + +```json +{ + "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4", + "name": "First Up Consultants | Beverage Shop - Satterfieldmouth", + "location": { + "lat": -89.2384, + "lon": -46.4012 + }, + "staff": { + "totalStaff": { + "fullTime": 8, + "partTime": 20 + } + }, + "sales": { + "totalSales": 75670, + "salesByCategory": [ + { + "categoryName": "Wine Accessories", + "totalSales": 34440 + }, + { + "categoryName": "Bitters", + "totalSales": 39496 + }, + { + "categoryName": "Rum", + "totalSales": 1734 + } + ] + }, + "promotionEvents": [ + { + "eventName": "Unbeatable Bargain Bash", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 6, + "Day": 23 + }, + "endDate": { + "Year": 2024, + "Month": 7, + "Day": 2 + } + }, + "discounts": [ + { + "categoryName": "Whiskey", + "discountPercentage": 7 + }, + { + "categoryName": "Bitters", + "discountPercentage": 15 + }, + { + "categoryName": "Brandy", + "discountPercentage": 8 + }, + { + "categoryName": "Sports Drinks", + "discountPercentage": 22 + }, + { + "categoryName": "Vodka", + "discountPercentage": 19 + } + ] + }, + { + "eventName": "Steal of a Deal Days", + "promotionalDates": { + "startDate": { + "Year": 2024, + "Month": 9, + "Day": 21 + }, + "endDate": { + "Year": 2024, + "Month": 9, + "Day": 29 + } + }, + "discounts": [ + { + "categoryName": "Organic Wine", + "discountPercentage": 19 + }, + { + "categoryName": "White Wine", + "discountPercentage": 20 + }, + { + "categoryName": "Sparkling Wine", + "discountPercentage": 19 + }, + { + "categoryName": "Whiskey", + "discountPercentage": 17 + }, + { + "categoryName": "Vodka", + "discountPercentage": 23 + } + ] + } + ] +} +``` + +### Example 1: Ranking stores by sales volume + +To rank all stores within the "First Up Consultants" company by sales volume, first run a query to partition the stores within the company. Then, sort the resulting stores in ascending order of sales volume and use the $rank operator to rank the sorted documents in the result set. + +```javascript +db.stores.aggregate([{ + "$match": { + "company": { + "$in": ["First Up Consultants"] + } + } +}, { + "$setWindowFields": { + "partitionBy": "$company", + "sortBy": { + "sales.totalSales": -1 + }, + "output": { + "rankBySales": { + "$rank": {} + } + } + } +}, { + "$project": { + "company": 1, + "name": 1, + "rankBySales": 1 + } +}]) +``` + +The first three results returned by this query are: + +```json +[ + { + "_id": "a0386810-b6f8-4b05-9d60-e536fb2b0026", + "name": "First Up Consultants | Electronics Stop - South Thelma", + "company": "First Up Consultants", + "rankBySales": 1 + }, + { + "_id": "ad8af64a-d5bb-4162-9bb6-e5104126566d", + "name": "First Up Consultants | Electronics Emporium - South Carmenview", + "company": "First Up Consultants", + "rankBySales": 2 + }, + { + "_id": "39acb3aa-f350-41cb-9279-9e34c004415a", + "name": "First Up Consultants | Bed and Bath Pantry - Port Antone", + "company": "First Up Consultants", + "rankBySales": 3 + } +] +``` diff --git a/api-reference/operators/window-operators/$shift.md b/api-reference/operators/window-operators/$shift.md new file mode 100644 index 0000000..a5e5328 --- /dev/null +++ b/api-reference/operators/window-operators/$shift.md @@ -0,0 +1,80 @@ +--- +title: $shift usage on DocumentDB +description: A window operator that shifts values within a partition and returns the shifted value. +type: operators +category: window-operators +--- + +# $shift + +The `$shift` operator is a window operator used in aggregation pipelines to shift values within a partition and return the shifted value. It is useful for operations where you need to compare values from adjacent documents in a sorted partition. + +## Syntax + +```javascript +{ + $shift: { + output: , + by: , + default: + } +} +``` + +## Parameters + +| Parameter | Description | +| --- | --- | +| **`output`** | Specifies the field or expression whose value will be shifted. | +| **`by`** | Specifies the number of positions to shift the value. Positive values shift forward, while negative values shift backward. | +| **`default`** | Specifies the default value to return if the shift operation goes out of bounds. | + +## Example(s) + +### Example 1: Shifting sales data + +This example demonstrates how to use `$shift` to calculate the previous sales value for each document in a sorted partition of sales data. + +```javascript +db.collection.aggregate([ + { + $setWindowFields: { + partitionBy: "$sales.salesByCategory.categoryName", + sortBy: { "sales.salesByCategory.totalSales": 1 }, + output: { + previousSales: { + $shift: { + output: "$sales.salesByCategory.totalSales", + by: -1, + default: null + } + } + } + } + } +]) +``` + +### Example 2: Shifting promotional event dates + +This example calculates the previous promotional event’s start date by sorting all events by startDate. Since we want to treat all events together, we don’t partition. + +```javascript +db.promotionEvents.aggregate([ + { + $setWindowFields: { + partitionBy: null, + sortBy: { "promotionalDates.startDate": 1 }, + output: { + previousStartDate: { + $shift: { + output: "$promotionalDates.startDate", + by: -1, + default: null + } + } + } + } + } +]) +``` diff --git a/architecture/index.md b/architecture/index.md index d2d6555..8045d58 100644 --- a/architecture/index.md +++ b/architecture/index.md @@ -1,3 +1,7 @@ - DocumentDB Architecture +--- +title: Architecture under the hood +description: Deep dive into DocumentDB's internal architecture, data structures, query processing, storage engine design, and distributed systems. +layout: coming-soon +--- -This section provides detailed information about DocumentDB's architecture and design principles. +We're building something amazing! The technical architecture documentation providing detailed information about DocumentDB's architecture and design principles is coming soon. diff --git a/architecture/navigation.yml b/architecture/navigation.yml new file mode 100644 index 0000000..b52cc14 --- /dev/null +++ b/architecture/navigation.yml @@ -0,0 +1,2 @@ +- title: Architecture under the hood + link: index.md diff --git a/documentdb-local/index.md b/documentdb-local/index.md index 4a46a5c..80c9a7a 100644 --- a/documentdb-local/index.md +++ b/documentdb-local/index.md @@ -1,6 +1,11 @@ -# DocumentDB-local -DocumentDB Local provides a lightweight, containerized environment for developing and testing applications locally, including prototyping and integration testing. +--- +title: DocumentDB Local +description: Learn how to install and run DocumentDB Local using Docker for local development and testing. Includes setup instructions, configuration options, and certificate management. +--- + +# DocumentDB Local +DocumentDB Local provides a lightweight, containerized environment for developing and testing applications locally, including prototyping and integration testing. ## Prerequisites @@ -110,4 +115,4 @@ For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ ## Reporting issues -If you encounter issues with using this version of DoucmenttDB, open an issue in the GitHub repository () and tag it with the label `documentdb-local`. \ No newline at end of file +If you encounter issues with using this version of DoucmenttDB, open an issue in the GitHub repository () and tag it with the label `documentdb-local`. diff --git a/documentdb-local/navigation.yml b/documentdb-local/navigation.yml new file mode 100644 index 0000000..8967d4d --- /dev/null +++ b/documentdb-local/navigation.yml @@ -0,0 +1,2 @@ +- title: DocumentDB Local + link: index.md diff --git a/getting-started/aws-setup.md b/getting-started/aws-setup.md index 78d6f3e..0f107ba 100644 --- a/getting-started/aws-setup.md +++ b/getting-started/aws-setup.md @@ -1,7 +1,12 @@ +--- +title: AWS Setup +description: Deploy and manage DocumentDB alongside AWS for a hybrid database strategy. +--- + # Multi-cloud with AWS DocumentDB Deploy and manage DocumentDB alongside AWS for a hybrid database strategy. ## Important Note -This guide covers deploying the open-source DocumentDB on AWS infrastructure. This is distinct from Amazon's DocumentDB service, which is a different product. While both support MongoDB compatibility, they are separate implementations with different features and capabilities. \ No newline at end of file +This guide covers deploying the open-source DocumentDB on AWS infrastructure. This is distinct from Amazon's DocumentDB service, which is a different product. While both support MongoDB compatibility, they are separate implementations with different features and capabilities. diff --git a/getting-started/azure-setup.md b/getting-started/azure-setup.md index 126dc5d..3960be9 100644 --- a/getting-started/azure-setup.md +++ b/getting-started/azure-setup.md @@ -1,3 +1,8 @@ +--- +title: Azure Setup +description: Deploy and manage DocumentDB on Micrtosoft Azure for a fully managed experience. +--- + # Multi-cloud with Azure Deploy and manage DocumentDB on Micrtosoft Azure for a fully managed experience. @@ -14,4 +19,4 @@ Deploy and manage DocumentDB on Micrtosoft Azure for a fully managed experience. - Custom deployment options - Manual management required -## Setup \ No newline at end of file +## Setup diff --git a/getting-started/gcp-setup.md b/getting-started/gcp-setup.md index c5c12fd..bfc619e 100644 --- a/getting-started/gcp-setup.md +++ b/getting-started/gcp-setup.md @@ -1,3 +1,8 @@ +--- +title: GCP Setup +description: Deploy and manage DocumentDB on Google Cloud Platform using various deployment options. +--- + # Multi-cloud with GCP Deploy and manage DocumentDB on Google Cloud Platform using various deployment options. diff --git a/getting-started/index.md b/getting-started/index.md index 9828196..92317ba 100644 --- a/getting-started/index.md +++ b/getting-started/index.md @@ -1,3 +1,8 @@ +--- +title: Getting Started +description: DocumentDB is an open-source document database platform built on PostgreSQL. It offers developers a fully permissive, open-source platform for document data stores. +--- + # Introduction to DocumentDB DocumentDB is an open-source document database platform built on PostgreSQL. It offers developers a fully permissive, open-source platform for document data stores. diff --git a/getting-started/mongo-shell-quickstart.md b/getting-started/mongo-shell-quickstart.md index d63b8d8..49f38fb 100644 --- a/getting-started/mongo-shell-quickstart.md +++ b/getting-started/mongo-shell-quickstart.md @@ -1,3 +1,8 @@ +--- +title: MongoDB Shell Quick Start +description: Learn how to set up and use DocumentDB with Node.js using the official MongoDB Node.js driver. +--- + # Node.js Setup Guide Learn how to set up and use DocumentDB with Node.js using the official MongoDB Node.js driver. diff --git a/getting-started/mongodb-migration.md b/getting-started/mongodb-migration.md index 29b64fd..949e887 100644 --- a/getting-started/mongodb-migration.md +++ b/getting-started/mongodb-migration.md @@ -1,7 +1,12 @@ +--- +title: MongoDB Migration Guide +description: This guide helps you migrate your existing MongoDB applications to DocumentDB while maintaining compatibility and leveraging PostgreSQL benefits. +--- + # MongoDB to DocumentDB Migration Guide This guide helps you migrate your existing MongoDB applications to DocumentDB while maintaining compatibility and leveraging PostgreSQL benefits. ## Overview -DocumentDB provides full MongoDB wire protocol compatibility, making migration straightforward for most applications. This guide covers the migration process, considerations, and best practices for transitioning from MongoDB to DocumentDB. \ No newline at end of file +DocumentDB provides full MongoDB wire protocol compatibility, making migration straightforward for most applications. This guide covers the migration process, considerations, and best practices for transitioning from MongoDB to DocumentDB. diff --git a/getting-started/navigation.yml b/getting-started/navigation.yml new file mode 100644 index 0000000..fd7b02c --- /dev/null +++ b/getting-started/navigation.yml @@ -0,0 +1,22 @@ +- title: Getting Started + link: index.md +- title: Visual Studio Code Quick Start + link: vscode-quickstart.md +- title: Visual Studio Code Extension Guide + link: vscode-extension-guide.md +- title: Node.js Setup Guide + link: nodejs-setup.md +- title: Python Setup Guide + link: python-setup.md +- title: Pre-built Packages + link: prebuilt-packages.md +- title: AWS Setup + link: aws-setup.md +- title: Azure Setup + link: azure-setup.md +- title: GCP Setup + link: gcp-setup.md +- title: YugabyteDB Setup + link: yugabyte-setup.md +- title: MongoDB Migration Guide + link: mongodb-migration.md diff --git a/getting-started/nodejs-setup.md b/getting-started/nodejs-setup.md index 996d2f5..c1cff0a 100644 --- a/getting-started/nodejs-setup.md +++ b/getting-started/nodejs-setup.md @@ -1,3 +1,8 @@ +--- +title: Node.js Setup Guide +description: Learn how to set up and use DocumentDB with Node.js using the official MongoDB Node.js driver. +--- + # Node.js Setup Guide Learn how to set up and use DocumentDB with Node.js using the official MongoDB Node.js driver. diff --git a/getting-started/prebuilt-packages.md b/getting-started/prebuilt-packages.md index 077db99..6fd2231 100644 --- a/getting-started/prebuilt-packages.md +++ b/getting-started/prebuilt-packages.md @@ -1,3 +1,8 @@ +--- +title: Pre-built Packages +description: Download and install DocumentDB using our pre-built packages for various platforms. +--- + # Pre-built Packages Download and install DocumentDB using our pre-built packages for various platforms. @@ -47,4 +52,4 @@ Download and install DocumentDB using our pre-built packages for various platfor # Run development version docker pull ghcr.io/microsoft/documentdb/documentdb-local:1.1.0-beta.3 - ``` \ No newline at end of file + ``` diff --git a/getting-started/python-setup.md b/getting-started/python-setup.md index dc7914a..9ceabed 100644 --- a/getting-started/python-setup.md +++ b/getting-started/python-setup.md @@ -1,3 +1,8 @@ +--- +title: Python Setup Guide +description: Learn how to set up and use DocumentDB with Python using the official MongoDB Python driver (PyMongo). +--- + # Python Setup Guide Learn how to set up and use DocumentDB with Python using the official MongoDB Python driver (PyMongo). diff --git a/getting-started/vscode-extension-guide.md b/getting-started/vscode-extension-guide.md index bf98552..e477e5d 100644 --- a/getting-started/vscode-extension-guide.md +++ b/getting-started/vscode-extension-guide.md @@ -1,3 +1,8 @@ +--- +title: Visual Studio Code Extension Guide +description: The DocumentDB for VS Code extension is a powerful, open-source GUI that helps you browse, manage, and query DocumentDB and MongoDB databases across any cloud, hybrid, or local environment. +--- + # DocumentDB for VS Code Extension The [DocumentDB for VS Code extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-documentdb) is a powerful, open-source GUI that helps you browse, manage, and query DocumentDB and MongoDB databases across any cloud, hybrid, or local environment. diff --git a/getting-started/vscode-quickstart.md b/getting-started/vscode-quickstart.md index 8fd401b..302709a 100644 --- a/getting-started/vscode-quickstart.md +++ b/getting-started/vscode-quickstart.md @@ -1,3 +1,8 @@ +--- +title: Visual Studio Code Quick Start +description: Get started with DocumentDB using the Visual Studio Code extension for a seamless development experience. +--- + # VS Code Extension Quick Start Get started with DocumentDB using the Visual Studio Code extension for a seamless development experience. @@ -92,4 +97,4 @@ Get started with DocumentDB using the Visual Studio Code extension for a seamles - Explore advanced querying capabilities in the [API Reference](../api-reference/index.md) - Learn about indexing strategies in the [Architecture](../architecture/index.md) section -- Connect your application using one of our [Language Guides](python-setup.md) \ No newline at end of file +- Connect your application using one of our [Language Guides](python-setup.md) diff --git a/getting-started/yugabyte-setup.md b/getting-started/yugabyte-setup.md index c25566a..0c85310 100644 --- a/getting-started/yugabyte-setup.md +++ b/getting-started/yugabyte-setup.md @@ -1,7 +1,12 @@ +--- +title: YugabyteDB Setup +description: Learn how to use DocumentDB alongside YugabyteDB for a comprehensive database solution. +--- + # DocumentDB Usage with YugabyteDB Learn how to use DocumentDB alongside YugabyteDB for a comprehensive database solution. ## Overview -YugabyteDB is a distributed SQL database that is PostgreSQL-compatible. Since DocumentDB is built on PostgreSQL, it can be integrated with YugabyteDB to combine the benefits of both systems. \ No newline at end of file +YugabyteDB is a distributed SQL database that is PostgreSQL-compatible. Since DocumentDB is built on PostgreSQL, it can be integrated with YugabyteDB to combine the benefits of both systems. diff --git a/postgres-api/functions.md b/postgres-api/functions.md new file mode 100644 index 0000000..cd1fe5f --- /dev/null +++ b/postgres-api/functions.md @@ -0,0 +1,61 @@ +--- +title: Functions +description: Complete reference for PostgreSQL extension functions including CRUD operations, collection management, user management, and utilities. +--- + +# Functions + +Comprehensive documentation for PostgreSQL extension functions and their usage patterns. + +## CRUD Operations + +Functions for creating, reading, updating, and deleting documents in collections. + +| Function | Documentation | +|----------|---------------| +| `aggregate_cursor_first_page()` | [documentdb/wiki/Functions#aggregate_cursor_first_page](https://github.com/microsoft/documentdb/wiki/Functions#aggregate_cursor_first_page) +| `count_query()` | [documentdb/wiki/Functions#count_query](https://github.com/microsoft/documentdb/wiki/Functions#count_query) +| `cursor_get_more()` | [documentdb/wiki/Functions#cursor_get_more](https://github.com/microsoft/documentdb/wiki/Functions#cursor_get_more) +| `delete()` | [documentdb/wiki/Functions#delete](https://github.com/microsoft/documentdb/wiki/Functions#delete) +| `distinct_query()` | [documentdb/wiki/Functions#distinct_query](https://github.com/microsoft/documentdb/wiki/Functions#distinct_query) +| `find_and_modify()` | [documentdb/wiki/Functions#find_and_modify](https://github.com/microsoft/documentdb/wiki/Functions#find_and_modify) +| `find_cursor_first_page()` | [documentdb/wiki/Functions#find_cursor_first_page](https://github.com/microsoft/documentdb/wiki/Functions#find_cursor_first_page) +| `insert()` | [documentdb/wiki/Functions#insert](https://github.com/microsoft/documentdb/wiki/Functions#insert) +| `insert_one()` | [documentdb/wiki/Functions#insert_one](https://github.com/microsoft/documentdb/wiki/Functions#insert_one) +| `list_collections_cursor_first_page()` | [documentdb/wiki/Functions#list_collections_cursor_first_page](https://github.com/microsoft/documentdb/wiki/Functions#list_collections_cursor_first_page) +| `list_indexes_cursor_first_page()` | [documentdb/wiki/Functions#list_indexes_cursor_first_page](https://github.com/microsoft/documentdb/wiki/Functions#list_indexes_cursor_first_page) +| `update()` | [documentdb/wiki/Functions#update](https://github.com/microsoft/documentdb/wiki/Functions#update) + +## Collection Management + +Functions for managing collections, views, and databases. + +| | Documentation | +| --- | --- | +| `coll_mod()` | [documentdb/wiki/Functions#coll_mod](https://github.com/microsoft/documentdb/wiki/Functions#coll_mod) +| `create_collection()` | [documentdb/wiki/Functions#create_collection](https://github.com/microsoft/documentdb/wiki/Functions#create_collection) +| `create_collection_view()` | [documentdb/wiki/Functions#create_collection_view](https://github.com/microsoft/documentdb/wiki/Functions#create_collection_view) +| `drop_collection()` | [documentdb/wiki/Functions#drop_collection](https://github.com/microsoft/documentdb/wiki/Functions#drop_collection) +| `drop_database()` | [documentdb/wiki/Functions#drop_database](https://github.com/microsoft/documentdb/wiki/Functions#drop_database) +| `rename_collection()` | [documentdb/wiki/Functions#rename_collection](https://github.com/microsoft/documentdb/wiki/Functions#rename_collection) +| `shard_collection()` | [documentdb/wiki/Functions#shard_collection](https://github.com/microsoft/documentdb/wiki/Functions#shard_collection) + +## User Management + +Functions for creating, updating, and managing database users. + +| | Documentation | +| --- | --- | +| `create_user()` | [documentdb/wiki/Functions#create_user](https://github.com/microsoft/documentdb/wiki/Functions#create_user) +| `drop_user()` | [documentdb/wiki/Functions#drop_user](https://github.com/microsoft/documentdb/wiki/Functions#drop_user) +| `update_user()` | [documentdb/wiki/Functions#update_user](https://github.com/microsoft/documentdb/wiki/Functions#update_user) +| `users_info()` | [documentdb/wiki/Functions#users_info](https://github.com/microsoft/documentdb/wiki/Functions#users_info) + +## Utility Functions + +Functions for retrieving version information and other utility operations. + +| Function | Documentation | +| --- | --- | +| `binary_extended_version()` | [documentdb/wiki/Functions#binary_extended_version](https://github.com/microsoft/documentdb/wiki/Functions#binary_extended_version) +| `binary_version()` | [documentdb/wiki/Functions#binary_version](https://github.com/microsoft/documentdb/wiki/Functions#binary_version) diff --git a/postgres-api/index.md b/postgres-api/index.md index 6afb041..c1b377d 100644 --- a/postgres-api/index.md +++ b/postgres-api/index.md @@ -1,3 +1,36 @@ -# PostgreSQL API +--- +title: Components +description: Learn about pg_documentdb_core and pg_documentdb_api PostgreSQL extensions that enable BSON support and document operations in Postgres. +--- -DocumentDB provides PostgreSQL compatibility, allowing you to use PostgreSQL tools and drivers to interact with DocumentDB. \ No newline at end of file +# Components + +The DocumentDB implementation consists of two key PostgreSQL extensions that work together to provide MongoDB-compatible document database functionality within PostgreSQL. + +## pg_documentdb_core + +pg_documentdb_core is a PostgreSQL extension that introduces BSON datatype support and operations for native Postgres. This core component is essential for enabling document-oriented NoSQL capabilities within a PostgreSQL environment. It provides the foundational data structures and functions required to handle BSON data types, which are crucial for performing CRUD operations on documents. + +### Key Features + +- **BSON Datatype Support:** Adds BSON (Binary JSON) datatype to PostgreSQL, allowing for efficient storage and manipulation of JSON-like documents. + +- **Native Operations:** Implements native PostgreSQL operations for BSON data, ensuring seamless integration and performance. + +- **Extensibility:** Serves as the core building block for additional functionalities and extensions within the DocumentDB ecosystem. + +## pg_documentdb_api + +pg_documentdb_api is the public API surface for DocumentDB, providing CRUD functionality on documents stored in the database. This component leverages the capabilities of pg_documentdb_core to offer a comprehensive set of APIs for managing document data within PostgreSQL. + +### Key Features + +- **CRUD Operations:** Provides a rich set of APIs for creating, reading, updating, and deleting documents. + +- **Advanced Queries:** Supports complex queries, including full-text searches, geospatial queries, and vector embeddings. + +- **Integration:** Works seamlessly with pg_documentdb_core to deliver robust document management capabilities. + +### Usage + +To use pg_documentdb_api, you need to have pg_documentdb_core installed and configured in your PostgreSQL environment. Once set up, you can leverage the APIs provided by pg_documentdb_api to perform various document operations. diff --git a/postgres-api/navigation.yml b/postgres-api/navigation.yml new file mode 100644 index 0000000..bf0b376 --- /dev/null +++ b/postgres-api/navigation.yml @@ -0,0 +1,4 @@ +- title: Components + link: index.md +- title: Functions + link: functions.md diff --git a/schema/navigation.schema.json b/schema/navigation.schema.json new file mode 100644 index 0000000..98c0e5c --- /dev/null +++ b/schema/navigation.schema.json @@ -0,0 +1,67 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Articles Navigation Configuration", + "description": "Schema for defining the navigation menu structure for article sections. This configuration creates sidebar or hierarchical navigation menus that help users browse through related documentation pages within a specific topic area.", + "type": "array", + "minItems": 1, + "maxItems": 50, + "items": { + "type": "object", + "description": "A single navigation item representing a page or section within the documentation. Each item creates a clickable link in the navigation menu that directs users to specific content.", + "required": [ + "title", + "link" + ], + "properties": { + "title": { + "type": "string", + "description": "The display text for this navigation item as it appears in the menu. Should be concise yet descriptive enough to clearly indicate the page content. Use consistent terminology and formatting across navigation items for better user experience.", + "minLength": 1, + "maxLength": 100, + "examples": [ + "Python Setup Guide", + "VS Code Extension Quick Start", + "MongoDB Shell Quick Start", + "Architecture under the hood", + "Components", + "Functions", + "Getting Started", + "Configuration Options" + ] + }, + "link": { + "type": "string", + "description": "The URL path where this navigation item links to. For internal documentation pages, use relative paths to Markdown files. External links can use absolute URLs with http:// or https:// protocols.", + "pattern": "^(\\./.*\\.md$|/.*\\.md$|[^/]+\\.md$|https?://.+)", + "minLength": 1, + "maxLength": 500, + "examples": [ + "file-name.md", + "/sub-folder/file-name.md", + "https://external-website.domain" + ] + }, + "description": { + "type": "string", + "description": "Optional brief description or subtitle for this navigation item. Can be used to provide additional context about the page content, displayed as helper text in the navigation menu.", + "minLength": 1, + "maxLength": 200, + "examples": [ + "Learn how to set up your Python development environment", + "Quick installation guide for the VS Code extension", + "Deep dive into the DocumentDB architecture" + ] + }, + "children": { + "type": "array", + "description": "Optional array of nested navigation items that appear as sub-items under this parent item. Use this to create hierarchical navigation structures with collapsible sections. Supports multiple levels of nesting for complex documentation structures.", + "minItems": 1, + "maxItems": 30, + "items": { + "$ref": "#/items" + } + } + }, + "additionalProperties": false + } +} \ No newline at end of file