diff --git a/source/connection/connect.txt b/source/connection/connect.txt index d056f043d..218014490 100644 --- a/source/connection/connect.txt +++ b/source/connection/connect.txt @@ -4,6 +4,12 @@ Connect to MongoDB ================== +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + .. facet:: :name: genre :values: reference @@ -200,3 +206,118 @@ class. Select the tab that corresponds to your preferred class. .build(); MongoClient mongoClient = MongoClients.create(settings); +Frequently Asked Questions +-------------------------- + +This section answers questions that may arise when +connecting to MongoDB. + +Why are there two types of ``MongoClient`` in the Java driver? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are two types of ``MongoClient`` because we wanted a cleaner API +for new users that didn't have the confusion of including multiple CRUD +Frequently AsAPIs. We wanted to ensure that the new CRUD API was available in a Java +package structure that would work well with Java module support +introduced in Java 9. + +Which type of ``MongoClient`` should I use? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +New applications generally use the ``com.mongodb.client.MongoClient`` interface, +which supports the following features: + +- Configuration with ``MongoClientSettings`` and ``ConnectionString``. You can create + instances of this interface by using factory methods defined in the ``com.mongodb.client.MongoClients`` + class. +- Access to the CRUD API by using ``MongoDatabase``, and from there, ``MongoCollection``. + +Use the ``com.mongodb.MongoClient`` class if you require support for the legacy API, which supports +the following features: + +- Configuration by using ``MongoClientOptions`` and ``MongoClientURI``. +- Access to the CRUD API by using ``DB``, and from there, ``DBCollection``. You can access this API + by using the ``getDB()`` method. + +For applications that require a mix of the new and legacy APIs, ``com.mongodb.MongoClient`` also supports +the following features: + +- Configuration by using ``MongoClientSettings`` and ``ConnectionString``, the only difference + being that you create instances via constructors instead of a factory class. +- Access to the CRUD API using ``MongoDatabase``, and from there, ``MongoCollection``. You can access this + API by using the ``getDatabase()`` method. + +How do I prevent the "java.lang.NoClassDefFoundError: com/mongodb/MongoClient" error? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You might encounter a ``java.lang.NoClassDefFoundError`` exception when your +Java runtime environment cannot locate a class file at runtime. When you +attempt to run application code that uses the {+driver-long+}, you must include +the appropriate driver JAR files on the classpath. + +If you receive this error after adding the {+driver-short+} JAR files to +your classpath, check the following items in your environment: + +- The JAR files exist in the locations specified by the classpath. +- The classpath syntax is correct. +- If you define the classpath in an environment variable, the Java runtime + environment uses that variable. +- If you use a dependency manager, it does not report any unresolvable conflicts. + +.. tip:: + + This error contains the package and class name, which can help you identify + which driver JAR might be missing from your classpath. To locate the + driver JAR that the error refers to, check each of the entries in the + :ref:`API documentation `. + +How do I prevent the "com.mongodb.MongoSecurityException" error? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Your application might throw this exception if you specify invalid or +incorrectly formatted credentials when connecting to a MongoDB deployment. + +If you receive this error when you attempt to connect to a MongoDB deployment, +check the following items in your code: + +- The connection URI corresponds to the correct MongoDB deployment. + To learn more about setting your connection URI, see :ref:`connection-uri`. + +- The credentials for the authentication mechanism that you specified are + correct. To learn how to specify your credentials, see the + :ref:`authentication-mechanisms` and :ref:`enterprise-authentication-mechanisms` + guides. + +- The name of the authentication database that you specified is correct. To + learn how to set up the users and roles for your MongoDB deployment, see + `Manage Users and Roles `__ + in the Server documentation. + +How do I prevent the "IllegalStateException: state should be: open" error? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You might encounter this exception if you call an operation on a ``MongoClient`` +instance that closed its connections to MongoDB. Once the ``close()`` method +is called on the ``MongoClient``, any further operation calls on that instance +throw this exception. + +To avoid this exception, do not call operations on ``MongoClient`` instance +after any code that calls ``close()`` on it. + +.. tip:: + + The code that closes the ``MongoClient`` instance might be difficult to + locate in certain cases. To locate potential sources of this exception, + search for the following cases: + + - Calls to ``close()`` on a ``MongoClient`` instance + - Operation calls on a ``MongoClient`` instance that are outside the scope + of the try-with-resources statement in which the ``MongoClient`` is + declared + + If your application uses a framework to manage the ``MongoClient`` + such as Spring Boot, check the documentation of the framework to locate the + best practices for managing the connection behavior. + + To learn more about accessing MongoDB from Spring Boot, see + `Spring Boot and MongoDB `__. \ No newline at end of file diff --git a/source/connection/mongoclientsettings.txt b/source/connection/mongoclientsettings.txt index 6aa860b71..c60580de3 100644 --- a/source/connection/mongoclientsettings.txt +++ b/source/connection/mongoclientsettings.txt @@ -591,4 +591,4 @@ to MongoDB: :end-before: end SslSettings :language: java :emphasize-lines: 3-4 - :dedent: + :dedent: \ No newline at end of file diff --git a/source/data-formats/document-data-format-bson.txt b/source/data-formats/document-data-format-bson.txt index 2739b4461..6973ff8e0 100644 --- a/source/data-formats/document-data-format-bson.txt +++ b/source/data-formats/document-data-format-bson.txt @@ -89,3 +89,52 @@ for that tool: If you are not using one of the preceding tools, you can include it in your project by downloading the JAR file directly from the `sonatype repository `__. + +Frequently Asked Questions +-------------------------- + +This section answers questions that may arise when using the BSON data format. + +How do I prevent the "IllegalArgumentException: Invalid BSON field name" error? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Your application might throw this exception if you pass an incorrectly formatted +document to an operation and you are using {+driver-short+} v4.7 or earlier. + +.. note:: + + In driver versions v4.8 and later, this error message was replaced by one + that includes more specific details on what was incorrectly formatted. + +For example, the driver throws this error when you call an update operation +and incorrectly omit the update operator as shown in the following code +example: + +.. code-block:: java + :emphasize-lines: 4 + :copyable: false + + // incorrectly formatted update document + collection.updateOne( + new Document().append("name", "fizz"), + new Document().append("name", "buzz") + ); + +To avoid this error, use the builder class for the appropriate operation. +The driver offers builder classes to create syntactically correct BSON for +MongoDB operations. The preceding example can be correctly expressed using +the builder classes, as shown in the following code example: + +.. code-block:: java + :emphasize-lines: 7 + :copyable: false + + // Builder class imports + import static com.mongodb.client.model.Filters.*; + import static com.mongodb.client.model.Updates.*; + + // ... + + collection.updateOne(eq("name", "fizz"), set("name", "buzz")); + +To learn more about the available builders classes, see the :ref:`` guide. diff --git a/source/data-formats/document-data-format-pojo.txt b/source/data-formats/document-data-format-pojo.txt index e663157e9..b8796e1fa 100644 --- a/source/data-formats/document-data-format-pojo.txt +++ b/source/data-formats/document-data-format-pojo.txt @@ -206,16 +206,44 @@ see the following API documentation: - `getDefaultCodecRegistry() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.html?is-external=true#getDefaultCodecRegistry()>`__ - `fromProviders() <{+api+}/apidocs/bson/org/bson/codecs/configuration/CodecRegistries.html#fromProviders(org.bson.codecs.configuration.CodecProvider...)>`__ -Summary -------- - -This guide describes how to convert data between BSON and the POJO format -by performing the following tasks: - -- Instantiate a ``PojoCodecProvider`` which contains codecs that define how to - encode and decode data between BSON and the POJO fields. -- Specify the **automatic** conversion behavior for the ``PojoCodecProvider`` - to apply the ``Codecs`` to any class and its properties. -- Add the ``PojoCodecProvider`` to a ``CodecRegistry``, and specify the - registry on an instance of a ``MongoDatabase`` or ``MongoCollection``. -- Perform CRUD operations that use the sample POJO class. \ No newline at end of file +Frequently Asked Questions +-------------------------- + +This section answers questions that may arise when storing +POJOs in MongoDB. + +Do I have to specify an ID field value myself? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +No, the ``PojoCodecProvider`` automatically generates an ObjectId. + +Can the ID field be a compound key? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Yes. For an example of this, see `our implementation `__ +in Github. + +Can I use polymorphism in a POJO accessor? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Yes, by using a discriminator. For more information, see the :ref:`Discriminators +` section of the POJO Customization guide. + +Can I mix private, protected, and public setters and getters? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +No. The native POJO codec assumes that getters and setters have the same +modifiers for each field. + +For example, the following methods throws an exception during encoding: + +.. code-block:: java + + private String getField(); + public String setField(String x); + +How do I fix: "org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class X."? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This exception means you must register a codec for the class since +none exist. \ No newline at end of file diff --git a/source/data-formats/pojo-customization.txt b/source/data-formats/pojo-customization.txt index 08e6db440..cfdf42d5f 100644 --- a/source/data-formats/pojo-customization.txt +++ b/source/data-formats/pojo-customization.txt @@ -759,4 +759,57 @@ a codec for ``enum`` types if you need one, such as the one in the default codec registry. See the documentation on the :ref:`default codec registry ` -For more information about how to register the codecs it includes. +for more information about how to register the codecs it includes. + +Frequently Asked Questions +-------------------------- + +This section answers questions that may arise when defining +data conversion logic. + +Can I control serialization of ``LocalDate``? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Yes, the {+driver-short+} v3.7 adds native support for ``JSR-310 Instant``, +``LocalDate`` and ``LocalDateTime``. + +Can I serialize a ``java.util.Date`` as a string in format **yyyy-mm-dd**? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Yes, you can build your own codec for this class and add it to the registry. + +Add the codec to the first in the list of providers, before the default codec +registry and before the ``PojoCodecProvider``: + +.. literalinclude:: /includes/faq/code-snippets/FaqExample.java + :language: java + :emphasize-lines: 3 + :dedent: + :start-after: start myDateAsStringCodec + :end-before: end myDateAsStringCodec + +Can I make POJOs read/write directly to the field and not use the getters/setters at all? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can configure the ``PojoCodecProvider`` to use the +``SET_PRIVATE_FIELDS_CONVENTION``, which sets a private field through +reflection if no public setter is available. + +How do I specify the collection name for a particular POJO class? Is there an annotation? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There is no annotation. We recommend adding a static string in your class as shown +in the following code: + +.. code-block:: java + + public class Person { + public static final String COLLECTION_NAME = "people"; + } + +The following snippet specifies the collection name for a particular +POJO class: + +.. code-block:: java + + database.getCollection(Person.COLLECTION_NAME, Person.class); \ No newline at end of file diff --git a/source/faq.txt b/source/faq.txt deleted file mode 100644 index d473191cf..000000000 --- a/source/faq.txt +++ /dev/null @@ -1,471 +0,0 @@ -.. _java-faq: - -=== -FAQ -=== - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -General -------- - -What if I can't connect to a MongoDB instance? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If you have trouble connecting to a MongoDB deployment, see -the :ref:`Connection Troubleshooting Guide ` -for possible solutions. - -Why are there two types of ``MongoClient`` in the Java driver? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -There are two types of ``MongoClient`` because we wanted a cleaner API -for new users that didn't have the confusion of including multiple CRUD -APIs. We wanted to ensure that the new CRUD API was available in a Java -package structure that would work well with Java module support -introduced in Java 9. - -Which type of ``MongoClient`` should I use? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -New applications generally use the -``com.mongodb.client.MongoClient`` interface, which supports: - -- Configuration with ``MongoClientSettings`` and ``ConnectionString``. You can create instances of this interface via factory methods defined in the ``com.mongodb.client.MongoClients`` class. -- CRUD API using ``MongoDatabase``, and from there, ``MongoCollection`` - -Use the ``com.mongodb.MongoClient`` class if you require support for the legacy API, which supports: - -- Configuration with ``MongoClientOptions`` and ``MongoClientURI`` -- CRUD API using ``DB``, and from there, ``DBCollection``. You can access this API via the ``getDB()`` method. - -For applications that require a mix of the new and legacy APIs, ``com.mongodb.MongoClient`` also supports: - -- Configuration with ``MongoClientSettings`` and ``ConnectionString``, the only difference being that you create instances via constructors instead of a factory class. -- CRUD API using ``MongoDatabase``, and from there, ``MongoCollection``. You can access this API via the ``getDatabase()`` method. - -How do I use the ``MongoClientSettings`` class? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can use the ``MongoClientSettings`` class to specify configurations for -``MongoClient`` instances. To construct ``MongoClientSettings`` instances, use the -``MongoClientSettings.Builder`` class. - -Here are the sections of our documentation that show how to perform different -tasks with the ``MongoClientSettings`` class: - -- :ref:`Specify Multiple Hosts ` -- :ref:`Enable TLS/SSL ` -- :ref:`Authenticate with Credentials ` -- :ref:`Enable Compression ` -- :ref:`Add Listeners For Driver and Database Events ` -- :ref:`Get the Default Codec Registry ` - -For more information about the ``MongoClientSettings`` class, see the -`API Documentation for MongoClientSettings <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.html>`__. - -.. _java-faq-connection-pool: - -How Does Connection Pooling Work in the Java Driver? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Every ``MongoClient`` instance has a built-in connection pool for each server -in your MongoDB topology. Connection pools open sockets on demand to -support concurrent MongoDB operations in your multi-threaded application. - -The maximum size of each connection pool is set by the ``maxPoolSize`` option, which -defaults to ``100``. If the number of in-use connections to a server reaches -the value of ``maxPoolSize``, the next request to that server will wait -until a connection becomes available. - -Each ``MongoClient`` instance opens two additional sockets per server in your -MongoDB topology for monitoring the server's state. - -For example, a client connected to a 3-node replica set opens 6 -monitoring sockets. It also opens as many sockets as needed to support -an application's threads on each server, up to -the value of ``maxPoolSize``. If ``maxPoolSize`` is ``100`` and the -application only uses the primary (the default), then only the primary -connection pool grows and there can be at most ``106`` total connections. If the -application uses a :ref:`read preference ` to query the -secondary nodes, their pools also grow and there can be ``306`` total connections. - -Additionally, connection pools are rate-limited such that each connection pool -can only create, at maximum, the value of ``maxConnecting`` connections -in parallel at any time. Any additional thread stops waiting in the -following cases: - -- One of the existing threads finishes creating a connection, or - an existing connection is checked back into the pool. -- The driver's ability to reuse existing connections improves due to - rate-limits on connection creation. - -You can set the minimum number of concurrent connections to -each server with the ``minPoolSize`` option, which defaults to ``0``. -The connection pool will be initialized with this number of sockets. If -sockets are closed due to any network errors, causing the total number -of sockets (both in use and idle) to drop below the minimum, more -sockets are opened until the minimum is reached. - -You can set the maximum number of milliseconds that a connection can -remain idle in the pool before being removed and replaced with -the ``maxIdleTimeMS`` option, which defaults to ``0`` (no limit). - -The following default configuration for a ``MongoClient`` works for most -applications: - -.. code-block:: java - - MongoClient client = new MongoClient("") - -Create a client once for each process, and reuse it for all -operations. It is a common mistake to create a new client for each -request, which is very inefficient. - -To support high numbers of concurrent MongoDB operations -within one process, you can increase ``maxPoolSize``. Once the pool -reaches its maximum size, additional threads wait for sockets -to become available. - -The driver does not limit the number of threads that -can wait for sockets to become available and it is the application's -responsibility to limit the size of its pool to bound queuing -during a load spike. Threads wait for the amount of time specified in -the ``waitQueueTimeoutMS`` option, which defaults to ``120000``, or 120 seconds. - -A thread that waits more than the length of time defined by -``waitQueueTimeoutMS`` for a socket raises a connection error. Use this -option if it is more important to bound the duration of operations -during a load spike than it is to complete every operation. - -When ``MongoClient.close()`` is called by any thread, the driver -closes all idle sockets and closes all sockets that are in -use as they are returned to the pool. - -How do I prevent the "java.lang.NoClassDefFoundError: com/mongodb/MongoClient" error? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You might encounter a ``java.lang.NoClassDefFoundError`` exception when your -Java runtime environment cannot locate a class file at runtime. When you -attempt to run application code that uses the {+driver-long+}, you must include -the appropriate driver JAR files on the classpath. - -If you receive this error after adding the {+driver-short+} JAR files to -your classpath, check the following items in your environment: - -- The JAR files exist in the locations specified by the classpath. -- The classpath syntax is correct. -- If you define the classpath in an environment variable, the Java runtime - environment uses that variable. -- If you use a dependency manager, it does not report any unresolvable conflicts. - -.. tip:: - - This error contains the package and class name, which can help you identify - which driver JAR might be missing from your classpath. To locate the - driver JAR that the error refers to, check each of the entries in the - :ref:`API documentation `. - - -How do I prevent the "com.mongodb.MongoSecurityException" error? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Your application might throw this exception if you specify invalid or -incorrectly formatted credentials when connecting to a MongoDB deployment. - -If you receive this error when you attempt to connect to a MongoDB deployment, -check the following items in your code: - -- The connection URI corresponds to the correct MongoDB deployment. - To learn more about setting your connection URI, see :ref:`connection-uri`. - -- The credentials for the authentication mechanism that you specified are - correct. To learn how to specify your credentials, see the - :ref:`java-authentication-mechanisms` section. - -- The name of the authentication database that you specified is correct. To - learn how to set up the users and roles for your MongoDB deployment, see - `Manage Users and Roles `__ - in the Server documentation. - -How do I prevent the "IllegalArgumentException: Invalid BSON field name" error? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Your application might throw this exception if you pass an incorrectly formatted -document to an operation and you are using a driver version v4.7 or earlier. - -.. note:: - - In driver versions v4.8 and later, this error message was replaced by one - that includes more specific details on what was incorrectly formatted. - -For example, the driver throws this error when you call an update operation -and incorrectly omit the update operator as shown in the following code -example: - -.. code-block:: java - :emphasize-lines: 4 - :copyable: false - - // incorrectly formatted update document - collection.updateOne( - new Document().append("name", "fizz"), - new Document().append("name", "buzz") - ); - -To avoid this error, use the builder class for the appropriate operation. -The driver offers builder classes to create syntactically correct BSON for -MongoDB operations. The prior example can be correctly expressed using -the builder classes as shown in the following code example: - -.. code-block:: java - :emphasize-lines: 7 - :copyable: false - - // Builder class imports - import static com.mongodb.client.model.Filters.*; - import static com.mongodb.client.model.Updates.*; - - // ... - - collection.updateOne(eq("name", "fizz"), set("name", "buzz")); - -To learn more about the available builders classes, see the :ref:`` documentation. - - -How do I prevent the "IllegalStateException: state should be: open" error? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You might encounter this exception if you call an operation on a ``MongoClient`` -instance that closed its connections to MongoDB. Once the ``close()`` method -is called on the ``MongoClient``, any further operation calls on that instance -throw this exception. - -To avoid this exception, do not call operations on ``MongoClient`` instance -after any code that calls ``close()`` on it. - -.. tip:: - - The code that closes the ``MongoClient`` instance might be difficult to - locate in certain cases. To locate potential sources of this exception, - search for the following cases: - - - Calls to ``close()`` on a ``MongoClient`` instance - - Operation calls on a ``MongoClient`` instance that are outside the scope - of the try-with-resources statement in which the ``MongoClient`` is - declared - - If your application uses a framework to manage the ``MongoClient`` - such as Spring Boot, check the documentation of the framework to locate the - best practices for managing the connection behavior. - - To learn more about accessing MongoDB from Spring Boot, see - `Spring Boot and MongoDB `__. - - -POJOs ------ - -Do I have to specify an ID field value myself? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -No, the ``PojoCodecProvider`` automatically generates an ObjectId. - -Can the ID field be a compound key? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Yes. For an example of this, see `our implementation `_ - -Can I use polymorphism in a POJO accessor? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Yes, by using a discriminator. - -What is a discriminator? -~~~~~~~~~~~~~~~~~~~~~~~~ - -A discriminator is a property that identifies a specific document -schema. You can use it for inheritance and storing multiple types of -documents within the same collection or parent document (if you embed -subdocuments). - -For example, if you have an ``Event`` class that you extend in Java, -such as ``MachineEvent`` or ``NetworkEvent``, using a discriminator -identifies which class the ``PojoCodecProvider`` must use to -serialize and deserialize the document. - -For more information, see the :ref:`POJO Customization guide -`. - -Can I control serialization of ``LocalDate``? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Yes, the 3.7 Java driver adds native support for ``JSR-310 Instant``, -``LocalDate`` & ``LocalDateTime``. - -Can I serialize a ``java.util.Date`` as a string in format **yyyy-mm-dd**? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Yes, you can build your own codec for this class and add it to the registry. - -Add the codec to the first in the list of providers, before the default codec -registry and before the ``PojoCodecProvider``: - -.. literalinclude:: /includes/faq/code-snippets/FaqExample.java - :language: java - :emphasize-lines: 3 - :dedent: - :start-after: start myDateAsStringCodec - :end-before: end myDateAsStringCodec - -Can I make POJOs read/write directly to the field and not use the getters/setters at all? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can configure the ``PojoCodecProvider`` to use the -``SET_PRIVATE_FIELDS_CONVENTION``, which sets a private field through -reflection if no public setter is available. - -Can I mix private, protected, and public setters and getters? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -No. The native POJO codec assumes that getters/setters have the same -modifiers for each field. - -For example, the following methods throws an exception during encoding: - -.. code-block:: java - - private String getField(); - public String setField(String x); - -How do I fix: "org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class X."? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This exception means you must register a codec for the class since -there is none at the moment. - -How do I specify the collection name for a particular POJO class? Is there an annotation? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -There is no annotation. We recommend adding a static string in your class as shown: - -.. code-block:: java - - public class Person { - public static final String COLLECTION_NAME = "people"; - } - -The following snippet specifies the collection name for a particular -POJO class: - -.. code-block:: java - - database.getCollection(Person.COLLECTION_NAME, Person.class); - -Legacy API ----------- - -.. _faq-legacy-connection: - -How do I connect to my MongoDB instance with the legacy API? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example shows how to connect to a MongoDB instance with the -legacy API and the current API. - -Imagine we are connecting to a collection that contains only this document: - -.. code-block:: json - :copyable: false - - {"_id": 1, "val": 1} - -.. tabs:: - - .. tab:: Legacy API - :tabid: legacy - - .. literalinclude:: /includes/fundamentals/code-snippets/LegacyAPI.java - :language: java - :dedent: - :start-after: start legacy-api-example - :end-before: end legacy-api-example - - .. tab:: Current API - :tabid: current - - .. literalinclude:: /includes/fundamentals/code-snippets/CurrentAPI.java - :language: java - :dedent: - :start-after: start current-api-example - :end-before: end current-api-example - -The output of the preceding code snippet resembles the following: - -.. code-block:: json - :copyable: false - - {"_id": 1, "val": 1} - -For more information about the legacy classes and methods used in the preceding example, -see the following API documentation pages: - -- `MongoClient <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClient.html>`__ -- `DB <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DB.html>`__ -- `DBCollection <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DBCollection.html>`__ -- `DBObject <{+api+}/apidocs/mongodb-driver-core/com/mongodb/DBObject.html>`__ -- `getDB() <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClient.html#getDB(java.lang.String)>`__ -- `getCollection() <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DB.html#getCollection(java.lang.String)>`__ -- `find() <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DBCollection.html#find()>`__ -- `one() <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DBCursor.html#one()>`__ - -See the :ref:`Migrate from the Legacy API ` page -for a list of differences between the legacy and current API. - -How do I use the legacy ``MongoClientOptions`` and ``MongoClientURI`` Classes? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Here is an example showing how to use the legacy ``MongoClientOptions`` and -``MongoClientURI`` classes to set your write concern: - -.. tabs:: - - .. tab:: Legacy API - :tabid: legacy - - .. literalinclude:: /includes/fundamentals/code-snippets/LegacyAPI.java - :language: java - :dedent: - :start-after: start legacy-api-mongoclientoptions-example - :end-before: end legacy-api-mongoclientoptions-example - - .. tab:: Current API - :tabid: current - - .. literalinclude:: /includes/fundamentals/code-snippets/CurrentAPI.java - :language: java - :dedent: - :start-after: start current-api-mongoclientsettings-example - :end-before: end current-api-mongoclientsettings-example - -For more information about the legacy classes and methods used in the preceding example, -see the following API Documentation pages: - -- `Legacy API documentation <{+api+}/apidocs/mongodb-driver-legacy/index.html>`__ -- `MongoClient <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClient.html>`__ -- `MongoClientOptions <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClientOptions.html>`__ -- `MongoClientURI <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClientURI.html>`__ - -See the :ref:`Migrate from the Legacy API ` page for a list -of differences between the legacy and current API. - -Support -------- - -If you are unable to find the answer to your question here, try our forums and -support channels listed in the :doc:`Issues and Help ` -section. diff --git a/source/includes/legacy-redirect.rst b/source/includes/legacy-redirect.rst index 6718f65e5..2b4140d32 100644 --- a/source/includes/legacy-redirect.rst +++ b/source/includes/legacy-redirect.rst @@ -1,5 +1,5 @@ .. tip:: Legacy API - If you are using the legacy API, - :ref:`see our FAQ page ` + If you are using the legacy API, see the + :ref:`FAQ section ` of the Legacy API guide to learn what changes you need to make to this code example. diff --git a/source/versioning/legacy.txt b/source/versioning/legacy.txt index 0bdbcbb79..fadb747cd 100644 --- a/source/versioning/legacy.txt +++ b/source/versioning/legacy.txt @@ -7,7 +7,7 @@ Migrate from the Legacy API .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol Overview @@ -17,7 +17,6 @@ On this page, you can identify the changes you must make to migrate from the legacy API to the current API. You can also learn about features unique to the current {+driver-short+} and the benefits of migrating to the new API. - The legacy API, packaged as the ``mongodb-driver-legacy`` JAR, contains the legacy synchronous Java driver and uses naming conventions used in earlier versions of the driver. @@ -166,3 +165,101 @@ In addition to the preceding items, consider the following changes: - `Bson <{+api+}/apidocs/bson/org/bson/conversions/Bson.html>`__ interface - `DBObject <{+api+}/apidocs/mongodb-driver-core/com/mongodb/DBObject.html>`__ interface +.. _java-legacy-api-faq: + +Frequently Asked Questions +-------------------------- + +This section answers questions that may arise about the legacy API. + +How do I connect to my MongoDB instance by using the legacy API? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Imagine we are connecting to a collection that contains only the following document: + +.. code-block:: json + :copyable: false + + {"_id": 1, "val": 1} + +The following example shows how to connect to this MongoDB collection by using +the legacy API and the current API: + +.. tabs:: + + .. tab:: Legacy API + :tabid: legacy + + .. literalinclude:: /includes/fundamentals/code-snippets/LegacyAPI.java + :language: java + :dedent: + :start-after: start legacy-api-example + :end-before: end legacy-api-example + + .. tab:: Current API + :tabid: current + + .. literalinclude:: /includes/fundamentals/code-snippets/CurrentAPI.java + :language: java + :dedent: + :start-after: start current-api-example + :end-before: end current-api-example + +The output of the preceding code snippet resembles the following: + +.. code-block:: json + :copyable: false + + {"_id": 1, "val": 1} + +For more information about the legacy classes and methods used in the preceding example, +see the following API documentation pages: + +- `MongoClient <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClient.html>`__ +- `DB <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DB.html>`__ +- `DBCollection <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DBCollection.html>`__ +- `DBObject <{+api+}/apidocs/mongodb-driver-core/com/mongodb/DBObject.html>`__ +- `getDB() <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClient.html#getDB(java.lang.String)>`__ +- `getCollection() <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DB.html#getCollection(java.lang.String)>`__ +- `find() <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DBCollection.html#find()>`__ +- `one() <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/DBCursor.html#one()>`__ + +See the :ref:`Migrate from the Legacy API ` page +for a list of differences between the legacy and current API. + +How do I use the legacy ``MongoClientOptions`` and ``MongoClientURI`` classes? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the legacy ``MongoClientOptions`` and +``MongoClientURI`` classes to set your write concern: + +.. tabs:: + + .. tab:: Legacy API + :tabid: legacy + + .. literalinclude:: /includes/fundamentals/code-snippets/LegacyAPI.java + :language: java + :dedent: + :start-after: start legacy-api-mongoclientoptions-example + :end-before: end legacy-api-mongoclientoptions-example + + .. tab:: Current API + :tabid: current + + .. literalinclude:: /includes/fundamentals/code-snippets/CurrentAPI.java + :language: java + :dedent: + :start-after: start current-api-mongoclientsettings-example + :end-before: end current-api-mongoclientsettings-example + +For more information about the legacy classes and methods used in the preceding example, +see the following API documentation: + +- `Legacy API documentation <{+api+}/apidocs/mongodb-driver-legacy/index.html>`__ +- `MongoClient <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClient.html>`__ +- `MongoClientOptions <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClientOptions.html>`__ +- `MongoClientURI <{+api+}/apidocs/mongodb-driver-legacy/com/mongodb/MongoClientURI.html>`__ + +See the :ref:`Migrate from the Legacy API ` page for a list +of differences between the legacy and current API. \ No newline at end of file