From a5aa8360c5e9866c447bffdab09df16b21bea34c Mon Sep 17 00:00:00 2001 From: seesharprun Date: Tue, 9 Dec 2025 11:19:06 -0500 Subject: [PATCH] Add reference files --- reference/commands/query-and-write/delete.md | 176 +++++++++ reference/commands/query-and-write/find.md | 349 +++++++++++++++++ .../commands/query-and-write/findandmodify.md | 246 ++++++++++++ reference/commands/query-and-write/getMore.md | 51 +++ reference/commands/query-and-write/insert.md | 356 ++++++++++++++++++ reference/commands/query-and-write/update.md | 201 ++++++++++ 6 files changed, 1379 insertions(+) create mode 100644 reference/commands/query-and-write/delete.md create mode 100644 reference/commands/query-and-write/find.md create mode 100644 reference/commands/query-and-write/findandmodify.md create mode 100644 reference/commands/query-and-write/getMore.md create mode 100644 reference/commands/query-and-write/insert.md create mode 100644 reference/commands/query-and-write/update.md diff --git a/reference/commands/query-and-write/delete.md b/reference/commands/query-and-write/delete.md new file mode 100644 index 0000000..890d367 --- /dev/null +++ b/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: + +```mongodb +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 + +```mongodb +db.stores.deleteMany({}) +``` + +### Example 2 - Delete a document that matches a specified query filter + +```mongodb +db.stores.deleteOne({"_id": "68471088-4d45-4164-ae58-a9428d12f310"}) +``` + +### Example 3 - Delete all documents that match a specified query filter + +```mongodb +db.stores.deleteMany({"promotionEvents.discounts.discountPercentage": 21}, {"limit": 0}) +``` + +### Example 3 - Delete only one of many documents that match a specified query filter + +```mongodb +db.stores.deleteMany({"promotionEvents.discounts.discountPercentage": 21}, {"limit": 1}) +``` + +## Related content + +- [insert with DocumentDB](insert) +- [update with DocumentDB](update) diff --git a/reference/commands/query-and-write/find.md b/reference/commands/query-and-write/find.md new file mode 100644 index 0000000..3c44c5e --- /dev/null +++ b/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: + +``` +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/reference/commands/query-and-write/findandmodify.md b/reference/commands/query-and-write/findandmodify.md new file mode 100644 index 0000000..99f802d --- /dev/null +++ b/reference/commands/query-and-write/findandmodify.md @@ -0,0 +1,246 @@ +--- +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 + +```javascript +[mongos] StoreData> db.stores.findAndModify({ +... query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" }, +... update: { $set: { "sales.totalSales": 550000.00 } }, +... new: true +... }) +{ + _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 + +```javascript +[mongos] StoreData> 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 +... }) + +{ + _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 + +```javascript +[mongos] StoreData> db.stores.findAndModify({ +... query: { "_id_": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" }, +... update: { $pull: { "promotionEvents": { "eventName": "Electronics Super Saver" } } }, +... new: true +... }) +null +[mongos] StoreData> db.stores.findAndModify({ +... query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" }, +... update: { $pull: { "promotionEvents": { "eventName": "Electronics Super Saver" } } }, +... new: true +... }) +{ + _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/reference/commands/query-and-write/getMore.md b/reference/commands/query-and-write/getMore.md new file mode 100644 index 0000000..19dad21 --- /dev/null +++ b/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: + +``` +{ + 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: + +```json +{ + getMore: 1234567890, + collection: "stores" +} +``` diff --git a/reference/commands/query-and-write/insert.md b/reference/commands/query-and-write/insert.md new file mode 100644 index 0000000..b42b203 --- /dev/null +++ b/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: + +``` +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. + +```javascript +{ + "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: + +```javascript +{ + "acknowledged": true, + "insertedIds": { + "0": "123456", + "1": "234567" + } +} +``` + +## Related content + +- [update with DocumentDB](update) +- [find with DocumentDB](find) diff --git a/reference/commands/query-and-write/update.md b/reference/commands/query-and-write/update.md new file mode 100644 index 0000000..5e92b8f --- /dev/null +++ b/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. + +```mongodb +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. + +```mongodb +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. + +```mongodb +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. + +```mongodb +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. + +```mongodb +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. + +```mongodb +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. + +```mongodb +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. + +```mongodb +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. + +```mongodb +db.stores.updateOne({"_id": "NonExistentDocId"}, {"$set": {"name": "Lakeshore Retail", "sales.totalSales": 0}}, {"upsert": true}) +``` + +## Related content + +- [insert with DocumentDB](insert) +- [delete with DocumentDB](delete)