diff --git a/reference/operators/evaluation-query/$expr.md b/reference/operators/evaluation-query/$expr.md new file mode 100644 index 0000000..d1a4efe --- /dev/null +++ b/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/reference/operators/evaluation-query/$jsonschema.md b/reference/operators/evaluation-query/$jsonschema.md new file mode 100644 index 0000000..8b173c3 --- /dev/null +++ b/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/reference/operators/evaluation-query/$mod.md b/reference/operators/evaluation-query/$mod.md new file mode 100644 index 0000000..e2c5d7e --- /dev/null +++ b/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/reference/operators/evaluation-query/$text.md b/reference/operators/evaluation-query/$text.md new file mode 100644 index 0000000..7319fa1 --- /dev/null +++ b/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" } + ] + } + ] + } +] +```