Skip to content

DOCSP-47273: FAQ reorg #644

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 121 additions & 0 deletions source/connection/connect.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
Connect to MongoDB
==================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference
Expand Down Expand Up @@ -200,3 +206,118 @@
.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

Check failure on line 221 in source/connection/connect.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidSubjunctive] Avoid the subjunctive 'would'. Raw Output: {"message": "[MongoDB.AvoidSubjunctive] Avoid the subjunctive 'would'.", "location": {"path": "source/connection/connect.txt", "range": {"start": {"line": 221, "column": 24}}}, "severity": "ERROR"}
introduced in Java 9.

Which type of ``MongoClient`` should I use?

Check failure on line 224 in source/connection/connect.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidSubjunctive] Avoid the subjunctive 'should'. Raw Output: {"message": "[MongoDB.AvoidSubjunctive] Avoid the subjunctive 'should'.", "location": {"path": "source/connection/connect.txt", "range": {"start": {"line": 224, "column": 31}}}, "severity": "ERROR"}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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.

Check failure on line 246 in source/connection/connect.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidObscure] Use 'through, by' instead of 'via'. Raw Output: {"message": "[MongoDB.AvoidObscure] Use 'through, by' instead of 'via'.", "location": {"path": "source/connection/connect.txt", "range": {"start": {"line": 246, "column": 35}}}, "severity": "ERROR"}
- 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 <java-api-landing>`.

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 <https://www.mongodb.com/docs/manual/tutorial/manage-users-and-roles/>`__
in the Server documentation.

How do I prevent the "IllegalStateException: state should be: open" error?

Check failure on line 296 in source/connection/connect.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidSubjunctive] Avoid the subjunctive 'should'. Raw Output: {"message": "[MongoDB.AvoidSubjunctive] Avoid the subjunctive 'should'.", "location": {"path": "source/connection/connect.txt", "range": {"start": {"line": 296, "column": 52}}}, "severity": "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 <https://www.mongodb.com/compatibility/spring-boot>`__.
2 changes: 1 addition & 1 deletion source/connection/mongoclientsettings.txt
Original file line number Diff line number Diff line change
Expand Up @@ -591,4 +591,4 @@ to MongoDB:
:end-before: end SslSettings
:language: java
:emphasize-lines: 3-4
:dedent:
:dedent:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably a whitespace thing? Not a big deal if you can't get rid of it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I'm not sure why this is showing up as edited

49 changes: 49 additions & 0 deletions source/data-formats/document-data-format-bson.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://repo1.maven.org/maven2/org/mongodb/bson/>`__.

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:`<java-builders>` guide.
54 changes: 41 additions & 13 deletions source/data-formats/document-data-format-pojo.txt
Original file line number Diff line number Diff line change
Expand Up @@ -206,16 +206,44 @@
- `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.
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?

Check failure on line 215 in source/data-formats/document-data-format-pojo.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'must' is preferred over 'have to'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'must' is preferred over 'have to'.", "location": {"path": "source/data-formats/document-data-format-pojo.txt", "range": {"start": {"line": 215, "column": 6}}}, "severity": "ERROR"}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

No, the ``PojoCodecProvider`` automatically generates an ObjectId.

Can the ID field be a compound key?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Yes. For an example of this, see `our implementation <https://github.com/niccottrell/mongo-java-tests/blob/master/src/test/PojoCompoundIdTest.java>`__
in Github.

Can I use polymorphism in a POJO accessor?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Yes, by using a discriminator. For more information, see the :ref:`Discriminators
<pojo-discriminators>` section of the POJO Customization guide.

Can I mix private, protected, and public setters and getters?

Check failure on line 232 in source/data-formats/document-data-format-pojo.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.CommaOxford] Use the Oxford comma in 'Can I mix private, protected, and public setters and '. Raw Output: {"message": "[MongoDB.CommaOxford] Use the Oxford comma in 'Can I mix private, protected, and public setters and '.", "location": {"path": "source/data-formats/document-data-format-pojo.txt", "range": {"start": {"line": 232, "column": 1}}}, "severity": "ERROR"}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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.
55 changes: 54 additions & 1 deletion source/data-formats/pojo-customization.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 <codecs-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);
Loading
Loading