diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index f08fcf22d..d0bbdc524 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -358,6 +358,35 @@ see the following API documentation: - `BulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html>`__ - `ordered() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html#ordered(boolean)>`__ +.. _java-usage-bulkwrite: + +Bulk Write Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs the following +actions: + +#. Creates a list of instances of the ``InsertOneModel``, ``UpdateOneModel``, + ``DeleteOneModel``, and ``ReplaceOneModel`` classes. +#. Runs an ordered ``bulkWrite()`` operation that performs the writes specified in the model list. + +.. io-code-block:: + + .. input:: /includes/crud/BulkWrite.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + Result statistics: + inserted: 3 + updated: 2 + deleted: 1 + .. _java-sync-client-bulk-write: Client Bulk Write @@ -594,55 +623,31 @@ Even though the write operation inserting a document with a duplicate key result in an error, the other operations are executed because the write operation is unordered. -To learn more about the methods and classes mentioned in this section, -see the following API documentation: +Additional Information +---------------------- -- `ClientBulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteOptions.html>`__ -- `ClientBulkWriteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteResult.html>`__ - -Summary -------- - -``MongoCollection.bulkWrite()`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To perform a bulk operation, you create and pass a list of -``WriteModel`` instances to the ``bulkWrite()`` method. - -There are 6 different ``WriteModel`` subtypes: ``InsertOneModel``, -``ReplaceOneModel``, ``UpdateOneModel``, ``UpdateManyModel``, -``DeleteOneModel`` and ``DeleteManyModel``. - -There are two ways to execute the ``bulkWrite()`` method: - -- Ordered, which performs the bulk operations in order until an error occurs, if any -- Unordered, which performs all the bulk operations in any order and reports errors - at the end, if any +API Documentation +~~~~~~~~~~~~~~~~~ -To learn more about the collection ``bulkWrite`` command, see the -:manual:`db.collection.bulkWrite() ` -method reference in the {+mdb-server+} Manual. +To learn more about the methods and classes used to perform bulk write +operations in this section, see the following API documentation: -``MongoClient.bulkWrite()`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +MongoCollection +``````````````` -When connecting to a deployment running {+mdb-server+} version 8.0 or later, you -can use the ``MongoClient.bulkWrite()`` method to perform bulk operations on multiple -databases and collections at once. +- `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#bulkWrite(com.mongodb.client.ClientSession,java.util.List)>`__ +- `BulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html>`__ +- `MongoBulkWriteException <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoBulkWriteException.html>`__ -To perform a client bulk operation, you create an pass a list of -``ClientNamespacedWriteModel`` instances to this method. +MongoClient +``````````` -There are six subtypes of ``ClientNamespacedWriteModel`` that are used to -represent write operations. To construct these write models, you can use the -corresponding ``ClientNamespacedWriteModel`` methods ``insertOne()``, ``updateOne()``, -``updateMany()``, ``replaceOne()``, ``deleteOne()``, and ``deleteMany()``. These -methods take a ``MongoNamespace`` object that defines which -database and collection to write to. +- `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCluster.html#bulkWrite(com.mongodb.client.ClientSession,java.util.List)>`__ +- `ClientBulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteOptions.html>`__ +- `ClientBulkWriteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteResult.html>`__ -The ``MongoClient.bulkWrite()`` method can also take a ``ClientBulkWriteOptions`` -object to specify different options for how the command is executed. +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ -To learn more about the client ``bulkWrite`` command, see the -:manual:`bulkWrite() ` method reference in the {+mdb-server+} -Manual. +- :manual:`MongoCollection.bulkWrite() ` +- :manual:`MongoClient.bulkWrite() ` diff --git a/source/crud/delete.txt b/source/crud/delete.txt index d4d70e883..1706fa1e6 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -4,6 +4,14 @@ Delete Documents ================ +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: remove, clear, reset, code example + :description: Learn about how to delete documents in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none @@ -147,14 +155,54 @@ collection: { "_id": 1, "color": "red", "qty": 5 } { "_id": 8, "color": "black", "qty": 8 } -For more information about the methods and classes mentioned in this guide, -see the following resources: - -- `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ API Documentation -- `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ API Documentation -- `findOneAndDelete() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#findOneAndDelete(org.bson.conversions.Bson)>`__ API Documentation -- `DeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteOptions.html>`__ API Documentation -- `FindOneAndDeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/FindOneAndDeleteOptions.html>`__ API Documentation -- :manual:`db.collection.deleteOne() ` Server Manual Entry -- :manual:`db.collection.deleteMany() ` Server Manual Entry -- :manual:`db.collection.findOneAndDelete() ` Server Manual Entry +.. _java-usage-deletemany: +.. _java-usage-deleteone: + +Delete Example: Full File +------------------------- + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs a delete one +operation and a delete many operation: + +.. io-code-block:: + + .. input:: /includes/crud/Delete.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + Deleted document count - query for one: 1 + Deleted document count - unlimited query: 4 + + +The queries in these examples use the ``eq()`` and ``lt()`` filters to query documents. For more +information about filters, see the `Filters Class +<{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html>`__ +API documentation. + +Additional Information +---------------------- + +API Documentation +~~~~~~~~~~~~~~~~~ + +For more information about the methods and classes used to delete documents, see the following API documentation: + +- `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ +- `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ +- `findOneAndDelete() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#findOneAndDelete(org.bson.conversions.Bson)>`__ +- `DeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteOptions.html>`__ +- `FindOneAndDeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/FindOneAndDeleteOptions.html>`__ +- `DeleteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/DeleteResult.html>`__ + +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ + +- :manual:`db.collection.deleteOne() ` +- :manual:`db.collection.deleteMany() ` +- :manual:`db.collection.findOneAndDelete() ` diff --git a/source/crud/insert.txt b/source/crud/insert.txt index 49fa6f734..35102847e 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -4,6 +4,14 @@ Insert Operations ================= +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: add, save, code example + :description: Learn about how to insert documents in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none @@ -30,28 +38,23 @@ The following sections focus on ``insertOne()`` and method, see our :ref:`guide on Bulk Operations `. -A Note About ``_id`` --------------------- - -When inserting a document, MongoDB enforces one constraint on your -documents by default: each document *must* contain a unique ``_id`` -field. +.. note:: The ``id_`` Field in Insert Operations -There are two ways to manage this field: + When inserting a document, MongoDB enforces one constraint on your + documents by default: each document *must* contain a unique ``_id`` value. + Duplicate ``_id`` values violate unique index constraints, resulting in a + ``WriteError``. -- You can manage this field yourself, ensuring each value you use is unique. -- You can let the driver automatically generate unique ObjectId values. + There are two ways to manage this field: -Unless you have provided strong guarantees for uniqueness, we recommend -you let the driver automatically generate ``_id`` values. + - You can manage this field yourself, ensuring each value you use is unique. + - You can let the driver automatically generate unique ObjectId values. -.. note:: - - Duplicate ``_id`` values violate unique index constraints, resulting - in a ``WriteError``. - -For additional information on unique indexes, see the manual entry on -:manual:`Unique Indexes `. + Unless you have provided strong guarantees for uniqueness, we recommend + you let the driver automatically generate ``_id`` values. + + For more information about unique indexes, see the manual entry on + :manual:`Unique Indexes `. .. _java-insertone: @@ -159,26 +162,48 @@ The output of the preceding code resembles the following: .. code-block:: :copyable: false - Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8] + Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, + 60930c3aa982931c20ef6cd8] -For more information about the methods and classes mentioned in this section, -see the following resources: +.. _java-usage-insertmany: +.. _java-usage-insertone: + +Insert Example: Full File +------------------------- + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs an insert one +operation and an insert many operation: + +.. io-code-block:: + + .. input:: /includes/crud/Insert.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + insertOne() document id: BsonObjectId{value=...} + insertMany() document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} -- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ API Documentation -- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ API Documentation -- Manual Explanation on :manual:`insertMany() ` -- Runnable :ref:`Insert Multiple Documents Example ` +Additional Information +---------------------- -Summary -------- +API Documentation +~~~~~~~~~~~~~~~~~ -There are three ways to perform an insert operation, but we focused on two: +For more information about the methods and classes used to insert documents, see the following API documentation: -- The ``insertOne()`` method inserts a single document. -- The ``insertMany()`` method inserts multiple documents. +- `insertOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`__ +- `InsertOneResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`__ +- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ +- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ -Both methods automatically generate an ``_id`` if you omit the field in -your document. +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ -If the insertion is successful, both methods return an instance -representing the ``_id`` of each new document. +- :manual:`db.collection.insertOne() ` +- :manual:`db.collection.insertMany() ` diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index a738def52..b86ca6871 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -4,10 +4,18 @@ Find Documents ============== +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: find, findOne, findMany, get, lookup, code example + :description: Learn about how to retrieve documents in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol Overview @@ -42,15 +50,24 @@ track of the color and quantity, which corresponds to the ``color`` and Find Operation -------------- -Use the find operation to retrieve a subset of your existing data in -MongoDB. You can specify what data to return including which documents -to retrieve, in what order to retrieve them, and how many to retrieve. - -To perform a find operation, call the ``find()`` method on an instance -of a ``MongoCollection``. This method searches a collection for documents that -match the query filter you provide. For more information about how to -specify a query, see our :ref:`Specify a Query -` guide. +Use the find operation to retrieve your documents from MongoDB. You can specify +which documents to retrieve, in what order to retrieve them, and how many to +retrieve. + +Call the ``find()`` method on an instance of a ``MongoCollection`` to filter for +documents that match the provided query. For more information about how to +specify a query, see our :doc:`Specify a Query ` guide. +You can then use methods such as ``forEach()`` or ``cursor()`` to retrieve +matching documents. For more information, see the `FindIterable +<{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ +API documentation. + +To retrieve a single document, you can add the ``first()`` method to your +``find()`` call. To choose a specific document, you can use the ``sort()`` +operation before selecting the first document. You may also want to use the +``limit()`` method to optimize memory usage. For more information, see the +server manual for more information about :manual:`memory optimization when using +the sort operation `. Example ~~~~~~~ @@ -80,8 +97,34 @@ The following shows the output of the preceding query: After the owner runs this query, they find two orders that matched the criteria. -For a runnable ``find()`` example, see our :ref:`Find Multiple -Documents ` page. +.. _java-usage-find: + +Find Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +This example is a complete, standalone file that performs the following actions: + +- Calls the ``find()`` method to retrieve 10 documents that has a ``runtime`` + value less than ``15`` minutes, applying a projection and sort to the results +- Calls the ``find()`` and ``first()`` methods to retrieve the document with the + highest ``imdb.rating`` that is has a ``runtime`` value less than ``15`` + minutes, applying a projection to the result + +.. io-code-block:: + + .. input:: /includes/crud/Find.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + 10 movies under 15 minutes: 10 Minutes, 3x3, 7:35 in the Morning, 8, 9, A Chairy Tale, A Corner in Wheat, A Gentle Spirit, A Is for Autism, A Movie, + + The highest rated movie under 15 minutes: {"title": "Andrè and Wally B.", "imdb": {"rating": 5.4, "votes": 3294, "id": 86855}} .. _retrieve-aggregate: @@ -97,7 +140,8 @@ instance of a ``MongoCollection``. This method accepts aggregation expressions to run in sequence. To perform aggregations, you can define aggregation stages that specify how to match documents, rename fields, and group values. For more information, see our -:ref:`Aggregation ` guide. +:ref:`Aggregation ` guide and the :ref:`Aggregation Expression +Operations ` page. Example ~~~~~~~ @@ -132,8 +176,27 @@ purchased color. For more information about how to construct an aggregation pipeline, see the {+mdb-server+} manual page on :manual:`Aggregation `. -For additional information on the methods mentioned on this page, see -the following API Documentation: +Additional Information +---------------------- + +API Documentation +~~~~~~~~~~~~~~~~~ + +For more information about the methods and classes used to retrieve documents +on this page, see the following API documentation: + +- `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ +- `first() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#first()>`__ +- `limit() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html#limit(int)>`__ +- `FindIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ +- `aggregate() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#aggregate(java.util.List)>`__ + +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ -- `MongoCollection.find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ -- `MongoCollection.aggregate() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#aggregate(java.util.List)>`__ +- :manual:`Collections ` +- :manual:`Query Documents ` +- :manual:`Aggregation ` + - :manual:`$sort ` + - :manual:`$limit ` +- :manual:`Aggregation stages ` diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 79441a230..16d185fd2 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -7,6 +7,14 @@ Update Documents ================ +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: update, upsert, correct, change, code example + :description: Learn about how to modify documents in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none @@ -170,4 +178,173 @@ documents match. to a document that violate unique index constraints on the collection. For more information about constraints on unique indexes, see :manual:`Unique Indexes ` in the - {+mdb-server+} manual. \ No newline at end of file + {+mdb-server+} manual. + +.. _java-usage-updatemany: +.. _java-usage-updateone: + +Update Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs an update one +operation and an update many operation: + +.. io-code-block:: + + .. input:: /includes/crud/Update.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + updateOne() modified document count: 1 + Upserted ID: null + + updateMany() modified document count: 242 + +.. _replace-operation: + +Replace +------- + +A replace operation substitutes one document from your collection. The +substitution occurs between a document your query filter matches and a +replacement document. + +The `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ +method removes all the existing fields and values in the +matching document (except the ``_id`` field) and substitutes it with the +replacement document. + +You can call the ``replaceOne()`` method on a ``MongoCollection`` +instance as follows: + +.. code-block:: java + + collection.replaceOne(, ); + +Replace Operation Parameters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``replaceOne()`` method has the following parameters: + +- ``query`` specifies a query filter with the criteria to match a + document to replace in your collection. +- ``replacement`` specifies fields and values of a new ``Document`` + object to replace the matched document. +- *(Optional)* ``replaceOptions`` specifies options that you can set to + customize how the driver performs the replace operation. To learn more + about this type, see the API documentation for `ReplaceOptions + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html>`__. + +Replace One Example +~~~~~~~~~~~~~~~~~~~ + +The paint store realizes they must update their inventory again. What they +thought was 20 cans of pink paint is actually 25 cans of orange paint. + +To update the inventory, call the ``replaceOne()`` method specifying the +following: + +- A query filter that matches documents where the ``color`` is "pink" +- A replacement document where the ``color`` is "orange" and the ``qty`` is "25" + +.. literalinclude:: /includes/fundamentals/code-snippets/Update.java + :language: java + :dedent: + :start-after: begin replaceOneExample + :end-before: end replaceOneExample + +The output of the preceding code resembles the following: + +.. code-block:: none + :copyable: false + + Matched document count: 1 + Modified document count: 1 + +The following shows the updated document: + +.. code-block:: json + :copyable: false + + { "_id": 5, "color": "orange", "qty": 25 } + +If multiple documents match the query filter specified in +the ``replaceOne()`` method, it replaces the first result. You can +specify a sort in a ``ReplaceOptions`` instance to apply an order to +matched documents before the server performs the replace operation, as +shown in the following code: + +.. literalinclude:: /includes/fundamentals/code-snippets/Update.java + :language: java + :dedent: + :start-after: begin replaceoptions + :end-before: end replaceoptions + +If zero documents match the query filter in the replace operation, +``replaceOne()`` makes no changes to documents in the collection. See +our :ref:`upsert guide ` to +learn how to insert a new document instead of replacing one if no +documents match. + +.. important:: + + The ``replaceOne()`` method cannot make changes to a document that + violate unique index constraints on the collection. + For more information about constraints on unique indexes, + see :manual:`Unique Indexes ` in the + {+mdb-server+} manual. + +.. _java-usage-replaceone: + +Replace One Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs a replace one operation. + +.. io-code-block:: + + .. input:: /includes/crud/ReplaceOne.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + Modified document count: 0 + Upserted id: BsonObjectId{ ... } + +Additional Information +---------------------- + +API Documentation +~~~~~~~~~~~~~~~~~ + +For more information about the methods and classes used on this page, see the following API documentation: + +- `updateOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ +- `updateMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ +- `UpdateOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOptions.html>`__ +- `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ +- `ReplaceOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html?is-external=true>`__ +- `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ +- `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ +- `combine() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#combine(org.bson.conversions.Bson...)>`__ +- `set() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#set(java.lang.String,TItem)>`__ +- `addToSet() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#addToSet(java.lang.String,TItem)>`__ +- `currentTimestamp() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#currentTimestamp(java.lang.String)>`__ + +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ + +- :manual:`db.collection.updateOne() ` +- :manual:`db.collection.updateMany() ` +- :manual:`db.collection.replaceOne() ` \ No newline at end of file diff --git a/source/includes/crud/BulkWrite.java b/source/includes/crud/BulkWrite.java new file mode 100644 index 000000000..bf111b362 --- /dev/null +++ b/source/includes/crud/BulkWrite.java @@ -0,0 +1,53 @@ +// Runs bulk write operations on a collection by using the Java driver + +package org.example; + +import java.util.Arrays; + +import org.bson.Document; + +import com.mongodb.MongoException; +import com.mongodb.bulk.BulkWriteResult; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.DeleteOneModel; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.ReplaceOneModel; +import com.mongodb.client.model.UpdateOneModel; +import com.mongodb.client.model.UpdateOptions; + +public class BulkWrite { + public static void main(String[] args) { + // Replace the uri string with your MongoDB deployment's connection string + String uri = ""; + + try (MongoClient mongoClient = MongoClients.create(uri)) { + MongoDatabase database = mongoClient.getDatabase("sample_mflix"); + MongoCollection collection = database.getCollection("movies"); + + // Runs a bulk write operation for the specified insert, update, delete, and replace operations + BulkWriteResult result = collection.bulkWrite( + Arrays.asList( + new InsertOneModel<>(new Document("name", "A Sample Movie")), + new InsertOneModel<>(new Document("name", "Another Sample Movie")), + new InsertOneModel<>(new Document("name", "Yet Another Sample Movie")), + + new UpdateOneModel<>(new Document("name", "A Sample Movie"), + new Document("$set", new Document("name", "An Old Sample Movie")), + new UpdateOptions().upsert(true)), + + new DeleteOneModel<>(new Document("name", "Yet Another Sample Movie")), + + new ReplaceOneModel<>(new Document("name", "Yet Another Sample Movie"), + new Document("name", "The Other Sample Movie").append("runtime", "42")) + )); + // Prints the number of inserted, updated, and deleted documents + System.out.println("Result statistics:" + + "\ninserted: " + result.getInsertedCount() + + "\nupdated: " + result.getModifiedCount() + + "\ndeleted: " + result.getDeletedCount()); + } + } +} \ No newline at end of file diff --git a/source/includes/crud/Delete.java b/source/includes/crud/Delete.java new file mode 100644 index 000000000..4658287d0 --- /dev/null +++ b/source/includes/crud/Delete.java @@ -0,0 +1,45 @@ +// Deletes documents from a collection by using the Java driver + +package org.example; + +import static com.mongodb.client.model.Filters.eq; + +import org.bson.Document; +import org.bson.conversions.Bson; + +import com.mongodb.MongoException; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.result.DeleteResult; + +import static com.mongodb.client.model.Filters.lt; + +public class Delete { + + public static void main(String[] args) { + // Replace the uri string with your MongoDB deployment's connection string + String uri = ""; + + try (MongoClient mongoClient = MongoClients.create(uri)) { + + MongoDatabase database = mongoClient.getDatabase("sample_mflix"); + MongoCollection collection = database.getCollection("movies"); + + Bson deleteOneQuery = eq("title", "The Garbage Pail Kids Movie"); + + // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" + DeleteResult result = collection.deleteOne(deleteOneQuery); + System.out.println("Deleted document count - delete one: " + result.getDeletedCount()); + + Bson deleteManyQuery = lt("imdb.rating", 1.9); + + // Deletes all documents that have an "imdb.rating" value less than 1.9 + result = collection.deleteMany(deleteManyQuery); + + // Prints the number of deleted documents + System.out.println("Deleted document count - delete many: " + result.getDeletedCount()); + } + } +} \ No newline at end of file diff --git a/source/includes/crud/Find.java b/source/includes/crud/Find.java new file mode 100644 index 000000000..4eeb48a8f --- /dev/null +++ b/source/includes/crud/Find.java @@ -0,0 +1,62 @@ +// Retrieves documents that match a query filter by using the Java driver + +package org.example; + +import static com.mongodb.client.model.Filters.lt; + +import org.bson.Document; +import org.bson.conversions.Bson; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Projections; +import com.mongodb.client.model.Sorts; + +import static com.mongodb.client.model.Filters.eq; + +public class Find { + public static void main( String[] args ) { + + // Replace the uri string with your MongoDB deployment's connection string + String uri = ""; + + try (MongoClient mongoClient = MongoClients.create(uri)) { + MongoDatabase database = mongoClient.getDatabase("sample_mflix"); + MongoCollection collection = database.getCollection("movies"); + + // Projects "title" and "imdb" fields, excludes "_id" + Bson projectionFields = Projections.fields( + Projections.include("title", "imdb"), + Projections.excludeId()); + + // Retrieves documents with a runtime of less than 15 minutes, applying the + // projection and a sorting in alphabetical order + FindIterable docs = collection.find(lt("runtime", 15)) + .projection(projectionFields) + .sort(Sorts.ascending("title")) + .limit(10); + + // Prints the titles of the queried documents + System.out.println("10 movies under 15 minutes: "); + docs.forEach(doc -> System.out.println("- " + doc.get("title"))); + System.out.println(); + + // Retrieves the document with the best imdb rating that is less + // than 15 minutes long, applying the projection + Document doc = collection.find(lt("runtime", 15)) + .projection(projectionFields) + .sort(Sorts.ascending("imdb.rating")) + .first(); + + // Prints title of the queried document + if (doc == null) { + System.out.println("No results found."); + } else { + System.out.println("The highest rated movie under 15 minutes: " + doc.toJson().get("title")); + } + } + } +} diff --git a/source/includes/usage-examples/code-snippets/InsertMany.java b/source/includes/crud/Insert.java similarity index 50% rename from source/includes/usage-examples/code-snippets/InsertMany.java rename to source/includes/crud/Insert.java index 8575fb7fe..517e8af58 100644 --- a/source/includes/usage-examples/code-snippets/InsertMany.java +++ b/source/includes/crud/Insert.java @@ -1,21 +1,23 @@ -// Inserts sample documents describing movies by using the Java driver +// Inserts a sample document describing a movie by using the Java driver -package usage.examples; +package org.example; import java.util.Arrays; -import java.util.List; import org.bson.Document; +import org.bson.types.ObjectId; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; +import com.mongodb.client.result.InsertOneResult; import com.mongodb.client.result.InsertManyResult; -public class InsertMany { +import java.util.List; +public class Insert { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = ""; @@ -24,22 +26,25 @@ public static void main(String[] args) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection collection = database.getCollection("movies"); + // Inserts a sample document describing a movie into the collection + InsertOneResult result = collection.insertOne(new Document() + .append("_id", new ObjectId()) + .append("title", "Ski Bloopers") + .append("genres", Arrays.asList("Documentary", "Comedy"))); + + // Prints the ID of the inserted document + System.out.println("Inserted document id - insert one: " + result.getInsertedId()); + // Creates two sample documents containing a "title" field List movieList = Arrays.asList( new Document().append("title", "Short Circuit 3"), new Document().append("title", "The Lego Frozen Movie")); - try { - // Inserts sample documents describing movies into the collection - InsertManyResult result = collection.insertMany(movieList); - - // Prints the IDs of the inserted documents - System.out.println("Inserted document ids: " + result.getInsertedIds()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to insert due to an error: " + me); - } + // Inserts sample documents describing movies into the collection + InsertManyResult result = collection.insertMany(movieList); + + // Prints the IDs of the inserted documents + System.out.println("Inserted document id - insert many: " + result.getInsertedIds()); } } } diff --git a/source/includes/usage-examples/code-snippets/ReplaceOne.java b/source/includes/crud/ReplaceOne.java similarity index 98% rename from source/includes/usage-examples/code-snippets/ReplaceOne.java rename to source/includes/crud/ReplaceOne.java index 8fe84bbef..8c7a83205 100644 --- a/source/includes/usage-examples/code-snippets/ReplaceOne.java +++ b/source/includes/crud/ReplaceOne.java @@ -1,6 +1,6 @@ // Replaces the first document that matches a filter by using the Java driver -package usage.examples; +package org.example; import static com.mongodb.client.model.Filters.eq; diff --git a/source/includes/crud/Update.java b/source/includes/crud/Update.java new file mode 100644 index 000000000..a80b7db4d --- /dev/null +++ b/source/includes/crud/Update.java @@ -0,0 +1,61 @@ +// Updates the first document that matches a query filter by using the Java driver + +package org.example; + +import org.bson.Document; +import org.bson.conversions.Bson; + +import com.mongodb.MongoException; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.UpdateOptions; +import com.mongodb.client.model.Updates; +import com.mongodb.client.result.UpdateResult; + +import static com.mongodb.client.model.Filters.gt; + +public class Update { + + public static void main(String[] args) { + // Replace the uri string with your MongoDB deployment's connection string + String uri = ""; + + try (MongoClient mongoClient = MongoClients.create(uri)) { + MongoDatabase database = mongoClient.getDatabase("sample_mflix"); + MongoCollection collection = database.getCollection("movies"); + + // Instructs the driver to insert a new document if none match the query + UpdateOptions options = new UpdateOptions().upsert(true); + + Document updateOneQuery = new Document().append("title", "Cool Runnings 2"); + + // Creates instructions to update the values of three document fields + Bson updateOneUpdates = Updates.combine( + Updates.set("runtime", 99), + Updates.addToSet("genres", "Sports"), + Updates.currentTimestamp("lastUpdated")); + + // Updates the first document that has a "title" value of "Cool Runnings 2" + UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options); + + // Prints the number of updated documents and the upserted document ID, if an upsert was performed + System.out.println("Number of documents updated - update one: " + result.getModifiedCount()); + System.out.println("Upserted document ID: " + result.getUpsertedId()); + + Bson updateManyQuery = gt("num_mflix_comments", 50); + + // Creates instructions to update the values of two document fields + Bson updateManyUpdates = Updates.combine( + Updates.addToSet("genres", "Frequently Discussed"), + Updates.currentTimestamp("lastUpdated")); + + // Updates documents that have a "num_mflix_comments" value over 50 + UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates); + + // Prints the number of updated documents + System.out.println("\nNumber of documents updated - update many: " + result.getModifiedCount()); + } + } +} diff --git a/source/includes/crud/example-intro.rst b/source/includes/crud/example-intro.rst index e2b1374dd..653f8277b 100644 --- a/source/includes/crud/example-intro.rst +++ b/source/includes/crud/example-intro.rst @@ -7,4 +7,4 @@ `. You can load them into your database on the free tier of MongoDB Atlas by following the :atlas:`Get Started with Atlas Guide - `. \ No newline at end of file + `. diff --git a/source/includes/usage-examples/code-snippets/BulkWrite.java b/source/includes/usage-examples/code-snippets/BulkWrite.java deleted file mode 100644 index d8cfd4452..000000000 --- a/source/includes/usage-examples/code-snippets/BulkWrite.java +++ /dev/null @@ -1,59 +0,0 @@ -// Runs bulk write operations on a collection by using the Java driver - -package usage.examples; - -import java.util.Arrays; - -import org.bson.Document; - -import com.mongodb.MongoException; -import com.mongodb.bulk.BulkWriteResult; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.DeleteOneModel; -import com.mongodb.client.model.InsertOneModel; -import com.mongodb.client.model.ReplaceOneModel; -import com.mongodb.client.model.UpdateOneModel; -import com.mongodb.client.model.UpdateOptions; - -public class BulkWrite { - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - try { - // Runs a bulk write operation for the specified insert, update, delete, and replace operations - BulkWriteResult result = collection.bulkWrite( - Arrays.asList( - new InsertOneModel<>(new Document("name", "A Sample Movie")), - new InsertOneModel<>(new Document("name", "Another Sample Movie")), - new InsertOneModel<>(new Document("name", "Yet Another Sample Movie")), - - new UpdateOneModel<>(new Document("name", "A Sample Movie"), - new Document("$set", new Document("name", "An Old Sample Movie")), - new UpdateOptions().upsert(true)), - - new DeleteOneModel<>(new Document("name", "Yet Another Sample Movie")), - - new ReplaceOneModel<>(new Document("name", "Yet Another Sample Movie"), - new Document("name", "The Other Sample Movie").append("runtime", "42")) - )); - // Prints the number of inserted, updated, and deleted documents - System.out.println("Result statistics:" + - "\ninserted: " + result.getInsertedCount() + - "\nupdated: " + result.getModifiedCount() + - "\ndeleted: " + result.getDeletedCount()); - - // Prints a message if any exceptions occur during the operations - } catch (MongoException me) { - System.err.println("The bulk write operation failed due to an error: " + me); - } - } - } -} \ No newline at end of file diff --git a/source/includes/usage-examples/code-snippets/DeleteMany.java b/source/includes/usage-examples/code-snippets/DeleteMany.java deleted file mode 100644 index 2eccff1e6..000000000 --- a/source/includes/usage-examples/code-snippets/DeleteMany.java +++ /dev/null @@ -1,42 +0,0 @@ -// Deletes multiple documents from a collection by using the Java driver - -package usage.examples; - -import static com.mongodb.client.model.Filters.lt; - -import org.bson.Document; -import org.bson.conversions.Bson; - -import com.mongodb.MongoException; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.result.DeleteResult; - -public class DeleteMany { - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - Bson query = lt("imdb.rating", 1.9); - - try { - // Deletes all documents that have an "imdb.rating" value less than 1.9 - DeleteResult result = collection.deleteMany(query); - - // Prints the number of deleted documents - System.out.println("Deleted document count: " + result.getDeletedCount()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to delete due to an error: " + me); - } - } - } -} \ No newline at end of file diff --git a/source/includes/usage-examples/code-snippets/DeleteOne.java b/source/includes/usage-examples/code-snippets/DeleteOne.java deleted file mode 100644 index 4ff02f20b..000000000 --- a/source/includes/usage-examples/code-snippets/DeleteOne.java +++ /dev/null @@ -1,41 +0,0 @@ -// Deletes a document from a collection by using the Java driver - -package usage.examples; - -import static com.mongodb.client.model.Filters.eq; - -import org.bson.Document; -import org.bson.conversions.Bson; - -import com.mongodb.MongoException; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.result.DeleteResult; - -public class DeleteOne { - - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - Bson query = eq("title", "The Garbage Pail Kids Movie"); - - try { - // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" - DeleteResult result = collection.deleteOne(query); - System.out.println("Deleted document count: " + result.getDeletedCount()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to delete due to an error: " + me); - } - } - } -} \ No newline at end of file diff --git a/source/includes/usage-examples/code-snippets/Find.java b/source/includes/usage-examples/code-snippets/Find.java deleted file mode 100644 index 596089b55..000000000 --- a/source/includes/usage-examples/code-snippets/Find.java +++ /dev/null @@ -1,48 +0,0 @@ -// Retrieves documents that match a query filter by using the Java driver - -package usage.examples; - -import static com.mongodb.client.model.Filters.lt; - -import org.bson.Document; -import org.bson.conversions.Bson; - -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoCursor; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.Projections; -import com.mongodb.client.model.Sorts; - -public class Find { - public static void main( String[] args ) { - - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - // Creates instructions to project two document fields - Bson projectionFields = Projections.fields( - Projections.include("title", "imdb"), - Projections.excludeId()); - - // Retrieves documents that match the filter, applying a projection and a descending sort to the results - MongoCursor cursor = collection.find(lt("runtime", 15)) - .projection(projectionFields) - .sort(Sorts.descending("title")).iterator(); - - // Prints the results of the find operation as JSON - try { - while(cursor.hasNext()) { - System.out.println(cursor.next().toJson()); - } - } finally { - cursor.close(); - } - } - } -} diff --git a/source/includes/usage-examples/code-snippets/InsertOne.java b/source/includes/usage-examples/code-snippets/InsertOne.java deleted file mode 100644 index 0949ea5ab..000000000 --- a/source/includes/usage-examples/code-snippets/InsertOne.java +++ /dev/null @@ -1,42 +0,0 @@ -// Inserts a sample document describing a movie by using the Java driver - -package usage.examples; - -import java.util.Arrays; - -import org.bson.Document; -import org.bson.types.ObjectId; - -import com.mongodb.MongoException; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.result.InsertOneResult; - -public class InsertOne { - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - try { - // Inserts a sample document describing a movie into the collection - InsertOneResult result = collection.insertOne(new Document() - .append("_id", new ObjectId()) - .append("title", "Ski Bloopers") - .append("genres", Arrays.asList("Documentary", "Comedy"))); - - // Prints the ID of the inserted document - System.out.println("Success! Inserted document id: " + result.getInsertedId()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to insert due to an error: " + me); - } - } - } -} diff --git a/source/includes/usage-examples/code-snippets/UpdateMany.java b/source/includes/usage-examples/code-snippets/UpdateMany.java deleted file mode 100644 index e155cf431..000000000 --- a/source/includes/usage-examples/code-snippets/UpdateMany.java +++ /dev/null @@ -1,48 +0,0 @@ -// Updates documents that match a query filter by using the Java driver - -package usage.examples; - -import static com.mongodb.client.model.Filters.gt; - -import org.bson.Document; -import org.bson.conversions.Bson; - -import com.mongodb.MongoException; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.Updates; -import com.mongodb.client.result.UpdateResult; - -public class UpdateMany { - - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - Bson query = gt("num_mflix_comments", 50); - - // Creates instructions to update the values of two document fields - Bson updates = Updates.combine( - Updates.addToSet("genres", "Frequently Discussed"), - Updates.currentTimestamp("lastUpdated")); - - try { - // Updates documents that have a "num_mflix_comments" value over 50 - UpdateResult result = collection.updateMany(query, updates); - - // Prints the number of updated documents - System.out.println("Modified document count: " + result.getModifiedCount()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to update due to an error: " + me); - } - } - } -} diff --git a/source/includes/usage-examples/code-snippets/UpdateOne.java b/source/includes/usage-examples/code-snippets/UpdateOne.java deleted file mode 100644 index 2bde4c1fc..000000000 --- a/source/includes/usage-examples/code-snippets/UpdateOne.java +++ /dev/null @@ -1,52 +0,0 @@ -// Updates the first document that matches a query filter by using the Java driver - -package usage.examples; - -import org.bson.Document; -import org.bson.conversions.Bson; - -import com.mongodb.MongoException; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.UpdateOptions; -import com.mongodb.client.model.Updates; -import com.mongodb.client.result.UpdateResult; - -public class UpdateOne { - - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - Document query = new Document().append("title", "Cool Runnings 2"); - - // Creates instructions to update the values of three document fields - Bson updates = Updates.combine( - Updates.set("runtime", 99), - Updates.addToSet("genres", "Sports"), - Updates.currentTimestamp("lastUpdated")); - - // Instructs the driver to insert a new document if none match the query - UpdateOptions options = new UpdateOptions().upsert(true); - - try { - // Updates the first document that has a "title" value of "Cool Runnings 2" - UpdateResult result = collection.updateOne(query, updates, options); - - // Prints the number of updated documents and the upserted document ID, if an upsert was performed - System.out.println("Modified document count: " + result.getModifiedCount()); - System.out.println("Upserted id: " + result.getUpsertedId()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to update due to an error: " + me); - } - } - } -} diff --git a/source/usage-examples/bulkWrite.txt b/source/usage-examples/bulkWrite.txt deleted file mode 100644 index c083a7c10..000000000 --- a/source/usage-examples/bulkWrite.txt +++ /dev/null @@ -1,115 +0,0 @@ -.. _java-usage-bulkwrite: - -======================= -Perform Bulk Operations -======================= - - - - -The ``bulkWrite()`` method performs batch write operations against a -*single* collection. This method reduces the number of network round trips from -your application to your MongoDB instance which increases the performance of your -application. Since you only receive the success status after -all the operations return, we recommend you use this if that meets the -requirements of your use case. - -You can specify one or more of the following write operations in -``bulkWrite()``: - -- Insert a document -- Update a document -- Update multiple documents -- Delete a document -- Delete multiple documents -- Replace a document - -The ``bulkWrite()`` method accepts the following parameters: - -- A ``List`` of objects that implement ``WriteModel``: the classes that - implement ``WriteModel`` correspond to the preceding write - operations. For example, the ``InsertOneModel`` class wraps the - ``insertOne()`` write method, which inserts a document. See the links - to the API documentation at the end of this page for more information - about each class. - -- ``BulkWriteOptions``: *optional* object that specifies settings such as - whether to ensure your MongoDB instance orders your write operations. - -.. note:: - - Retryable writes run on {+mdb-server+} versions 3.6 or later in bulk - write operations unless they include one or more instances of - ``UpdateManyModel`` or ``DeleteManyModel``. - -.. tip:: - - By default, MongoDB executes operations in a bulk write in the - specified order. During an ordered bulk write, if - an error occurs during the processing of an operation, MongoDB returns - without processing the remaining operations in the list. - - In contrast, when you set the ``ordered`` option to ``false``, MongoDB - continues to process the remaining write operations in the list even in the - event of an error. Unordered operations are usually faster since - MongoDB can execute them in parallel, but only use an - unordered bulk write if the order of your write operations is not - important. - -The ``bulkWrite()`` method returns a ``BulkWriteResult`` object that -contains information about the write operation results including the number -of documents inserted, modified, and deleted. - -If one or more of your operations attempts to set a value that violates a -unique index on your collection, an exception is raised that should look -something like this: - -.. code-block:: sh - :copyable: false - - The bulk write operation failed due to an error: Bulk write operation error on server . Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error collection: ... }]. - -Similarly, if you attempt to perform a bulk write against a collection -that uses schema validation and one or more of your write operations -provide an unexpected format, you might encounter exceptions. - -Example -------- - -The following code sample performs an ordered bulk write operation on the -``movies`` collection in the ``sample_mflix`` database. The example call -to ``bulkWrite()`` includes examples of the ``InsertOneModel``, -``UpdateOneModel``, and ``DeleteOneModel``. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/BulkWrite.java - :language: java - -The output of the preceding code resembles the following: - -.. code-block:: none - :copyable: false - - Result statistics: - inserted: 3 - updated: 2 - deleted: 1 - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following resources: - -- :manual:`Unique Index ` Server Manual Entry -- :manual:`Schema Validation ` Server Manual Entry -- `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#bulkWrite(java.util.List,com.mongodb.client.model.BulkWriteOptions)>`__ API Documentation -- `BulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html>`__ API Documentation -- `BulkWriteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/bulk/BulkWriteResult.html>`__ API Documentation -- `InsertOneModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/InsertOneModel.html>`__ API Documentation -- `UpdateOneModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOneModel.html>`__ API Documentation -- `UpdateManyModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateManyModel.html>`__ API Documentation -- `DeleteOneModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteOneModel.html>`__ API Documentation -- `DeleteManyModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteManyModel.html>`__ API Documentation -- `ReplaceOneModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOneModel.html>`__ API Documentation - diff --git a/source/usage-examples/delete-operations.txt b/source/usage-examples/delete-operations.txt deleted file mode 100644 index 811d30db6..000000000 --- a/source/usage-examples/delete-operations.txt +++ /dev/null @@ -1,15 +0,0 @@ -================= -Delete Operations -================= - -.. meta:: - :description: Learn by example: how to delete data from MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Delete One - Delete Many - -- :doc:`Delete a Document ` -- :doc:`Delete Multiple Documents ` diff --git a/source/usage-examples/deleteMany.txt b/source/usage-examples/deleteMany.txt deleted file mode 100644 index 7fc4bbf7c..000000000 --- a/source/usage-examples/deleteMany.txt +++ /dev/null @@ -1,58 +0,0 @@ -.. _java-usage-deletemany: - -========================= -Delete Multiple Documents -========================= - - - -You can delete multiple documents from a collection in a single operation -by calling the ``deleteMany()`` method on a ``MongoCollection`` object. - -To specify which documents to delete, pass a query filter that matches -the documents you want to delete. If you provide an empty document, -MongoDB matches all documents in the collection and deletes them. While -you can use ``deleteMany()`` to delete all documents in a collection, -consider using the ``drop()`` method instead for better performance. - -Upon successful deletion, this method returns an instance of -``DeleteResult``. You can retrieve information such as the number of -documents deleted by calling the ``getDeletedCount()`` method on the -``DeleteResult`` instance. - -If your delete operation fails, the driver raises an exception. For more -information on the types of exceptions raised under specific conditions, -see the API documentation for ``deleteMany()``, linked at the bottom of -this page. - -Example -------- - -The following snippet deletes multiple documents from the ``movies`` -collection in the ``sample_mflix`` database. - -The query filter passed to the ``deleteMany()`` method matches all -movie documents that contain a ``rating`` of less than **1.9** in the ``imdb`` -subdocument. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/DeleteMany.java - :language: java - -When you run the example, you should see output that reports the number of -documents deleted in your call to ``deleteMany()``. - -.. code-block:: none - :copyable: false - - Deleted document count: 4 - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ -- `DeleteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/DeleteResult.html>`__ -- `drop() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#drop()>`__ diff --git a/source/usage-examples/deleteOne.txt b/source/usage-examples/deleteOne.txt deleted file mode 100644 index ff2557481..000000000 --- a/source/usage-examples/deleteOne.txt +++ /dev/null @@ -1,60 +0,0 @@ -.. _java-usage-deleteone: - -================= -Delete a Document -================= - - - -You can delete a single document from a collection using the ``deleteOne()`` -method on a ``MongoCollection`` object. The method accepts a query filter -that matches the document you want to delete. If you do not specify -a filter, MongoDB matches the first document in the collection. The -``deleteOne()`` method only deletes the first document matched. - -This method returns an instance of ``DeleteResult`` which contains information -including how many documents were deleted as a result of the operation. - -If your delete operation fails, the driver raises an exception. For more -information on the types of exceptions raised under specific conditions, -see the API documentation for ``deleteOne()``, linked at the bottom of -this page. - -Example -------- - -The following snippet deletes a single document from the ``movies`` -collection of the ``sample_mflix`` database. The example uses the ``eq()`` -filter to match movies with the ``title`` exactly matching the text -``'The Garbage Pail Kids Movie'``. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/DeleteOne.java - :language: java - -When you run the example, if the query filter you passed in your call to -``deleteOne()`` matches a document and removes it, you should see output -that looks something like this: - -.. code-block:: none - :copyable: false - - Deleted document count: 1 - -If your query filter does not match a document in your collection, -your call to ``deleteOne()`` removes no documents and returns the following: - -.. code-block:: none - :copyable: false - - Deleted document count: 0 - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ -- `DeleteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/DeleteResult.html>`__ -- `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ diff --git a/source/usage-examples/find-operations.txt b/source/usage-examples/find-operations.txt deleted file mode 100644 index 712144c6d..000000000 --- a/source/usage-examples/find-operations.txt +++ /dev/null @@ -1,15 +0,0 @@ -=============== -Find Operations -=============== - -.. meta:: - :description: Learn by example: how to create queries and retrieve data from MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Find One - Find Many - -- :doc:`Find a Document ` -- :doc:`Find Multiple Documents ` diff --git a/source/usage-examples/find.txt b/source/usage-examples/find.txt deleted file mode 100644 index d5ee25489..000000000 --- a/source/usage-examples/find.txt +++ /dev/null @@ -1,77 +0,0 @@ -.. _java-usage-find: - -======================= -Find Multiple Documents -======================= - - - -You can query for multiple documents in a collection by calling the ``find()`` -method on a ``MongoCollection`` object. Pass a query filter to the -``find()`` method to query for and return documents that match the filter in -the collection. If you do not include a filter, MongoDB returns all the -documents in the collection. - -For more information about querying MongoDB with the Java driver, see our -:doc:`guide on Querying Documents `. - -You can also chain methods to the ``find()`` method such as ``sort()`` which -organizes the matched documents in a specified order and -``projection()`` which configures the included fields in the -returned documents. - -For more information about the ``sort()`` method, see our -:doc:`guide on Sorting `. -For more information about the ``projection()`` method, see our -:doc:`guide on Projections ` - -The ``find()`` method returns an instance of ``FindIterable``, a class -that offers several methods to access, organize, and traverse the results. -``FindIterable`` also inherits methods from its parent class, -``MongoIterable`` which implements the core Java interface ``Iterable``. - -You can call the ``iterator()`` method on the ``MongoIterable`` which -returns a ``MongoCursor`` instance that you can use to traverse the results. -You can call methods on the ``MongoCursor`` such as ``hasNext()`` to check -whether additional results exist, or ``next()`` to return the next document -in the collection. If no documents match the query, calling ``hasNext()`` -returns ``false`` and therefore calling ``next()`` throws an exception. - -If you call ``next()`` on the iterator either after it has returned the final -result or when no results exist, it throws an exception of type -``java.util.NoSuchElementException``. Always use ``hasNext()`` to check that -additional results exist before you call ``next()``. - - -Example -------- - -The following snippet finds and prints all documents that match a query on -the ``movies`` collection. It uses the following objects and methods: - -- A **query filter** that is passed to the ``find()`` method. The ``lt()`` - filter matches only movies with a runtime of less than 15 minutes. - -- A **sort** that organizes returned documents in descending order by - title ("Z" before "A"). - -- A **projection** that includes the objects in the ``title`` and ``imdb`` - fields and excludes the ``_id`` field using the helper method - ``excludeId()``. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/Find.java - :language: java - - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `FindIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ -- `MongoIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html>`__ -- `MongoCursor <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCursor.html>`__ -- `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ - diff --git a/source/usage-examples/findOne.txt b/source/usage-examples/findOne.txt deleted file mode 100644 index f6bfd7366..000000000 --- a/source/usage-examples/findOne.txt +++ /dev/null @@ -1,69 +0,0 @@ -.. _java-usage-findone: - -=============== -Find a Document -=============== - - - -You can retrieve a single document in a collection by chaining together -the ``find()`` and ``first()`` methods on a ``MongoCollection`` object. -You can pass a query filter to the ``find()`` method to query for and -return documents that match the filter in the collection. If you do not -include a filter, MongoDB returns all the documents in the collection. The -``first()`` method returns the first matching document. - -For more information about querying MongoDB with the Java driver, see our -:doc:`guide on Querying Documents `. - -You can also chain other methods to the ``find()`` method -such as ``sort()`` which organizes the matched documents in a specified order, and -``projection()`` which configures the fields included in the returned documents. - -For more information about the ``sort()`` method, see our -:doc:`guide on Sorting `. -For more information about the ``projection()`` method, see our -:doc:`guide on Projections ` - -The ``find()`` method returns an instance of ``FindIterable``, a class -that offers several methods to access, organize, and traverse the results. -``FindIterable`` also inherits methods from its parent class, -``MongoIterable`` such as ``first()``. - -The ``first()`` method returns the first document from the retrieved results -or ``null`` if there are no results. - - -Example -------- - -The following snippet finds a single document from the ``movies`` collection. -It uses the following objects and methods: - -- A **query filter** that is passed to the ``find()`` method. The ``eq`` - filter matches only movies with the title exactly matching the text - ``'The Room'``. - -- A **sort** that organizes matched documents in descending order by - rating, so if our query matches multiple documents the returned - document is the one with the highest rating. - -- A **projection** that includes the objects in the ``title`` and ``imdb`` - fields and excludes the ``_id`` field using the helper method - ``excludeId()``. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/FindOne.java - :language: java - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `FindIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ -- `MongoIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html>`__ -- `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ -- `first() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#first()>`__ - diff --git a/source/usage-examples/insert-operations.txt b/source/usage-examples/insert-operations.txt deleted file mode 100644 index 0c4b9975e..000000000 --- a/source/usage-examples/insert-operations.txt +++ /dev/null @@ -1,15 +0,0 @@ -================= -Insert Operations -================= - -.. meta:: - :description: Learn by example: how to insert data into MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Insert One - Insert Many - -- :doc:`Insert a Document ` -- :doc:`Insert Multiple Documents ` diff --git a/source/usage-examples/insertMany.txt b/source/usage-examples/insertMany.txt deleted file mode 100644 index 303238958..000000000 --- a/source/usage-examples/insertMany.txt +++ /dev/null @@ -1,51 +0,0 @@ -.. _java-usage-insertmany: - -========================= -Insert Multiple Documents -========================= - - - -You can insert multiple documents into a collection in a single -operation by calling the ``insertMany()`` method on a ``MongoCollection`` -object. To insert them, add your ``Document`` objects to a ``List`` and pass -that ``List`` as an argument to ``insertMany()``. If you call the ``insertMany()`` method -on a collection that does not exist yet, the server creates it for you. - -Upon successful insertion, ``insertMany()`` returns an instance of -``InsertManyResult``. You can retrieve information such as the ``_id`` -fields of the documents you inserted by calling the ``getInsertedIds()`` -method on the ``InsertManyResult`` instance. - -If your insert operation fails, the driver raises an exception. For more -information on the types of exceptions raised under specific conditions, -see the API documentation for ``insertMany()``, linked at the bottom of -this page. - -Example -------- - -The following snippet inserts multiple documents into the ``movies`` -collection. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/InsertMany.java - :language: java - -When you run the example, you should see output that resembles the following -with the inserted documents' ``ObjectId`` values in each of the value fields: - -.. code-block:: none - :copyable: false - - Inserted document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ -- `Document <{+api+}/apidocs/bson/org/bson/Document.html>`__ -- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ diff --git a/source/usage-examples/insertOne.txt b/source/usage-examples/insertOne.txt deleted file mode 100644 index 203683884..000000000 --- a/source/usage-examples/insertOne.txt +++ /dev/null @@ -1,52 +0,0 @@ -.. _java-usage-insertone: - -================= -Insert a Document -================= - - - -You can insert a single document into a collection using the ``insertOne()`` -method on a ``MongoCollection`` object. To insert a document, construct a -``Document`` object that contains the fields and values that you want to -store. If you call the ``insertOne()`` method on a collection that does -not exist yet, the server automatically creates it for you. - -Upon a successful insertion, ``insertOne()`` returns an instance of -``InsertOneResult``. You can retrieve information such as the ``_id`` -field of the document you inserted by calling the ``getInsertedId()`` -method on the ``InsertOneResult`` instance. - -If your insert operation fails, the driver raises an exception. For more -information on the types of exceptions raised under specific conditions, -see the API documentation for ``insertOne()``, linked at the bottom of -this page. - -Example -------- - -The following snippet inserts a single document into the ``movies`` -collection. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/InsertOne.java - :language: java - -When you run the example, you should see output that resembles the following -with the inserted document's ``ObjectId`` in the value field: - -.. code-block:: none - :copyable: false - - Inserted document id: BsonObjectId{value=...} - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `insertOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`__ -- `Document <{+api+}/apidocs/bson/org/bson/Document.html>`__ -- `InsertOneResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`__ - diff --git a/source/usage-examples/replaceOne.txt b/source/usage-examples/replaceOne.txt deleted file mode 100644 index 62c6b5402..000000000 --- a/source/usage-examples/replaceOne.txt +++ /dev/null @@ -1,124 +0,0 @@ -.. _java-usage-replaceone: - -================== -Replace a Document -================== - - - -You can replace a single document using the ``replaceOne()`` method on -a ``MongoCollection`` object. This method removes all the existing fields -and values from a document (except the ``_id`` field) and substitutes it -with your replacement document. - -The ``replaceOne()`` method accepts a query filter that matches the -document you want to replace and a replacement document that contains the -data you want to save in place of the matched document. The ``replaceOne()`` -method only replaces the first document that matches the filter. - -You can optionally pass an instance of ``ReplaceOptions`` to the ``replaceOne()`` method in -order to specify the method's behavior. For example, if you set the ``upsert`` -field of the ``ReplaceOptions`` object to ``true``, the operation inserts -a new document from the fields in the replacement document if no documents -match the query filter. See the link to the ``ReplaceOptions`` API -documentation at the bottom of this page for more information. - -Upon successful execution, the ``replaceOne()`` method returns an instance -of ``UpdateResult``. You can retrieve information such as the number of -documents modified by calling the ``getModifiedCount()`` method. You can also -retrieve the value of the document's ``_id`` field by calling the -``getUpsertedId()`` method if you set ``upsert(true)`` in the -``ReplaceOptions`` instance and the operation resulted in the insertion of a new document. - -If your replacement operation fails, the driver raises an exception. -For example, if you try to specify a value for the immutable field -``_id`` in your replacement document that differs from the original -document, the method throws a ``MongoWriteException`` with the message: - -.. code-block:: none - :copyable: false - - After applying the update, the (immutable) field '_id' was found to have been altered to _id: ObjectId('...) - -If your replacement document contains a change that violates unique index -rules, the method throws a ``MongoWriteException`` with an error -message that resembles the following: - -.. code-block:: none - :copyable: false - - E11000 duplicate key error collection: ... - -For more information about the types of exceptions raised under specific -conditions, see the API documentation for ``replaceOne()``, linked at the -bottom of this page. - -Example -------- - -In this example, we replace the first match of our query filter in the -``movies`` collection of the ``sample_mflix`` database with a replacement -document. All the fields except for the ``_id`` field are deleted from the -original document and are substituted by the replacement document. - -Before the ``replaceOne()`` operation runs, the original document contains -several fields describing the movie. After the operation runs, the resulting -document contains only the fields specified by the replacement document -(``title`` and ``fullplot``) and the ``_id`` field. - -The following snippet uses the following objects and methods: - -- A **query filter** that is passed to the ``replaceOne()`` method. The ``eq`` - filter matches only movies with the title exactly matching the text - ``'Music of the Heart'``. - -- A **replacement document** that contains the document that replaces the - matching document if it exists. - -- A **ReplaceOptions** object with the ``upsert`` option set to ``true``. - This option specifies that the method should insert the data contained in - the replacement document if the query filter does not match any documents. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/ReplaceOne.java - :language: java - -After you run the example, you should see output that looks something like -this: - -.. code-block:: none - :copyable: false - - Modified document count: 1 - Upserted id: null - -Or if the example resulted in an upsert: - -.. code-block:: none - :copyable: false - - Modified document count: 0 - Upserted id: BsonObjectId{value=...} - -If you query the replaced document, the output resembles the following: - -.. code-block:: none - :copyable: false - - Document { - { _id=..., - title=50 Violins, - fullplot=A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music - } - } - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `ReplaceOne <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ -- `ReplaceOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html?is-external=true>`__ -- `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ -- `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ diff --git a/source/usage-examples/update-operations.txt b/source/usage-examples/update-operations.txt deleted file mode 100644 index 0f8e93d37..000000000 --- a/source/usage-examples/update-operations.txt +++ /dev/null @@ -1,17 +0,0 @@ -=========================== -Update & Replace Operations -=========================== - -.. meta:: - :description: Learn by example: how to update and replace data in MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Update One - Update Many - Replace One - -- :doc:`Update a Document ` -- :doc:`Update Multiple Documents ` -- :doc:`Replace a Document ` diff --git a/source/usage-examples/updateMany.txt b/source/usage-examples/updateMany.txt deleted file mode 100644 index cbdc791dd..000000000 --- a/source/usage-examples/updateMany.txt +++ /dev/null @@ -1,117 +0,0 @@ -.. _java-usage-updatemany: - -========================= -Update Multiple Documents -========================= - - - -You can update multiple documents using the ``updateMany()`` method on -a ``MongoCollection`` object. The method accepts a **filter** that matches the -document you want to update and an **update** statement that instructs the -driver how to change the matching document. The ``updateMany()`` method updates -all the documents in the collection that match the filter. - -To perform an update with the ``updateMany()`` method, you must pass -a query filter and an update document. The query filter specifies which -documents in the collection to match and the update document provides -instructions on what changes to make to them. - -You can optionally pass an instance of ``UpdateOptions`` to the ``updateMany()`` method in -order to modify the behavior of the call. For example, if you set the -``upsert`` field of the ``UpdateOptions`` object to ``true`` and no documents -match the specified query filter, the operation inserts a new document -composed of the fields from both the query and update document. - -Upon successful execution, the ``updateMany()`` method returns an instance -of ``UpdateResult``. You can retrieve information such as the number of -documents modified by calling the ``getModifiedCount()`` method. If you -specified ``upsert(true)`` in an ``UpdateOptions`` object and the -operation results in an insert, you can retrieve the ``_id`` field of the -new document by calling the ``getUpsertedId()`` method on the -``UpdateResult`` instance. - -If your update operation fails, the driver raises an exception and does not update -any of the documents matching the filter. For example, if you try to set -a value for the immutable field ``_id`` in your update document, the -``updateMany()`` method does not update any documents and throws a -``MongoWriteException`` with the message: - -.. code-block:: none - :copyable: false - - Performing an update on the path '_id' would modify the immutable field '_id' - -If your update document contains a change that violates unique index -rules, the method throws a ``MongoWriteException`` with an error -message that resembles the following: - -.. code-block:: none - :copyable: false - - E11000 duplicate key error collection: ... - -For more information about the types of exceptions raised under specific -conditions, see the API documentation for ``updateMany()``, linked at the -bottom of this page. - -Example -------- - -In this example, we update documents that match our query in the ``movies`` -collection of the ``sample_mflix`` database. We perform the following -updates to the matching documents: - -- Add ``Frequently Discussed`` to the array of ``genres`` only if it does not - already exist -- Set the value of ``lastUpdated`` to the current time. - -We use the ``Updates`` builder, a factory class that contains static -helper methods to construct the update document. While you can pass an update -document instead of using the builder, the builder provides type checking and -simplified syntax. Read our -:ref:`guide on Updates ` in the Builders -section for more information. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/UpdateMany.java - :language: java - -After you run the example, you should see output that looks something like -this: - -.. code-block:: none - :copyable: false - - Modified document count: 53 - -If you query the updated document or documents, they should look something like -this: - -.. code-block:: none - :copyable: false - - [ - Document { - { _id=..., - plot=..., - genres=[..., Frequently Discussed, ...], - ... - lastUpdated=Timestamp{...} - } - }, - ... - ] - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `UpdateMany <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ -- `UpdateOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOptions.html>`__ -- `combine() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#combine(org.bson.conversions.Bson...)>`__ -- `addToSet() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#addToSet(java.lang.String,TItem)>`__ -- `currentTimestamp() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#currentTimestamp(java.lang.String)>`__ -- `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ diff --git a/source/usage-examples/updateOne.txt b/source/usage-examples/updateOne.txt deleted file mode 100644 index 8aba7942d..000000000 --- a/source/usage-examples/updateOne.txt +++ /dev/null @@ -1,122 +0,0 @@ -.. _java-usage-updateone: - -================= -Update a Document -================= - - - -You can update a single document using the ``updateOne()`` method on -a ``MongoCollection`` object. The method accepts a **filter** that matches the -document you want to update and an **update** statement that instructs the -driver how to change the matching document. The ``updateOne()`` method only -updates the first document that matches the filter. - -To perform an update with the ``updateOne()`` method, you must pass -a query filter and an update document. The query filter specifies the criteria -for which document to perform the update on and the update document provides -instructions on what changes to make to it. - -You can optionally pass an instance of ``UpdateOptions`` to the ``updateOne()`` method in -order to specify the method's behavior. For example, if you set the ``upsert`` field of -the ``UpdateOptions`` object to ``true``, the operation inserts a new -document from the fields in both the query and update document if no documents -match the query filter. See the link to the ``UpdateOptions`` API -documentation at the bottom of this page for more information. - -Upon successful execution, the ``updateOne()`` method returns an instance -of ``UpdateResult``. You can retrieve information such as the number of -documents modified by calling the ``getModifiedCount()`` method, or the -value of the ``_id`` field by calling the ``getUpsertedId()`` method if you -specified ``upsert(true)`` in an ``UpdateOptions`` instance. - -If your update operation fails, the driver raises an exception. -For example, if you try to set a value for the immutable field ``_id`` in -your update document, the method throws a ``MongoWriteException`` with the -message: - -.. code-block:: none - :copyable: false - - Performing an update on the path '_id' would modify the immutable field '_id' - -If your update document contains a change that violates unique index -rules, the method throws a ``MongoWriteException`` with an error -message that resembles the following: - -.. code-block:: none - :copyable: false - - E11000 duplicate key error collection: ... - -For more information about the types of exceptions raised under specific -conditions, see the API documentation for ``updateOne()``, linked at the -bottom of this page. - -Example -------- - -In this example, we update the first match for our query in the ``movies`` -collection of the ``sample_mflix`` database. We perform the following -updates to the matching document: - -- Set the value of ``runtime`` to ``99`` -- Add ``Sports`` to the array of ``genres`` only if it does not already - exist -- Set the value of ``lastUpdated`` to the current time. - -We use the ``Updates`` builder, a factory class that contains static -helper methods, to construct the update document. While you can pass an update -document instead of using the builder, the builder provides type checking and -simplified syntax. For more information about the ``Updates`` builder, see our -:ref:`guide about Updates `. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/UpdateOne.java - :language: java - -After you run the example, you should see output that looks something like this: - -.. code-block:: none - :copyable: false - - Modified document count: 1 - Upserted id: null - -Or if the example resulted in an upsert: - -.. code-block:: none - :copyable: false - - Modified document count: 0 - Upserted id: BsonObjectId{value=...} - - -If you query the updated document, the output resembles the following: - -.. code-block:: none - :copyable: false - - Document { - { _id=..., - plot=..., - genres=[Adventure, Comedy, Family, Sports], - runtime=99, - ... - lastUpdated=Timestamp{...} - } - } - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `UpdateOne <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ -- `UpdateOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOptions.html>`__ -- `combine() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#combine(org.bson.conversions.Bson...)>`__ -- `set() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#set(java.lang.String,TItem)>`__ -- `addToSet() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#addToSet(java.lang.String,TItem)>`__ -- `currentTimestamp() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#currentTimestamp(java.lang.String)>`__ -- `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__