From 52eb179be331995ee3cc5f843188921a4a54ff2c Mon Sep 17 00:00:00 2001 From: seesharprun Date: Tue, 9 Dec 2025 11:32:55 -0500 Subject: [PATCH] Add reference files --- .../operators/field-update/$currentdate.md | 200 +++++++++++ reference/operators/field-update/$inc.md | 156 ++++++++ reference/operators/field-update/$mul.md | 294 ++++++++++++++++ reference/operators/field-update/$rename.md | 202 +++++++++++ .../operators/field-update/$setoninsert.md | 332 ++++++++++++++++++ 5 files changed, 1184 insertions(+) create mode 100644 reference/operators/field-update/$currentdate.md create mode 100644 reference/operators/field-update/$inc.md create mode 100644 reference/operators/field-update/$mul.md create mode 100644 reference/operators/field-update/$rename.md create mode 100644 reference/operators/field-update/$setoninsert.md diff --git a/reference/operators/field-update/$currentdate.md b/reference/operators/field-update/$currentdate.md new file mode 100644 index 0000000..504d088 --- /dev/null +++ b/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/reference/operators/field-update/$inc.md b/reference/operators/field-update/$inc.md new file mode 100644 index 0000000..d5ed5ff --- /dev/null +++ b/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/reference/operators/field-update/$mul.md b/reference/operators/field-update/$mul.md new file mode 100644 index 0000000..fea8e68 --- /dev/null +++ b/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/reference/operators/field-update/$rename.md b/reference/operators/field-update/$rename.md new file mode 100644 index 0000000..d98dfff --- /dev/null +++ b/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/reference/operators/field-update/$setoninsert.md b/reference/operators/field-update/$setoninsert.md new file mode 100644 index 0000000..e97bb84 --- /dev/null +++ b/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.