Skip to content

Commit 1bc27b8

Browse files
committed
DOCSP-41121 Connect to MongoDB
1 parent ae8646c commit 1bc27b8

File tree

4 files changed

+271
-3
lines changed

4 files changed

+271
-3
lines changed

source/connect.txt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ Connect to MongoDB
2222
:titlesonly:
2323
:maxdepth: 1
2424

25+
/connect/mongoclient
2526
/connect/stable-api
26-
..
27-
.. /connect/mongoclient
27+
/connect/connection-options
28+
2829
.. /connect/connection-targets
29-
.. /connect/connection-options
3030
.. /connect/tls
3131
.. /connect/network-compression
3232
.. /connect/server-selection

source/connect/connection-options.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.. _kotlin-sync-connection-options:

source/connect/mongoclient.txt

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
.. _kotlin-sync-mongoclient:
2+
3+
====================
4+
Create a MongoClient
5+
====================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: connection string, URI, server, Atlas, settings, client
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
To connect to a MongoDB deployment, you need two things:
24+
25+
- A **connection URI**, also known as a *connection string*, which tells {+driver-short+}
26+
which MongoDB deployment to connect to.
27+
- A **MongoClient** object, which creates the connection to the MongoDB deployment
28+
and lets you perform operations on it.
29+
30+
You can also use either of these components to customize the way {+driver-short+} behaves
31+
while connected to MongoDB.
32+
33+
This guide shows you how to create a connection string and use a ``MongoClient`` object
34+
to connect to MongoDB.
35+
36+
.. _kotlin-sync-connection-uri:
37+
38+
Connection URI
39+
--------------
40+
41+
A standard connection string includes the following components:
42+
.. Any ref for authentication? Are we planning on making a page for authentication?
43+
44+
.. list-table::
45+
:widths: 20 80
46+
:header-rows: 1
47+
48+
* - Component
49+
- Description
50+
51+
* - ``mongodb://``
52+
53+
- Required. A prefix that identifies this as a string in the
54+
standard connection format.
55+
56+
* - ``username:password``
57+
58+
- Optional. Authentication credentials. If you include these, the client
59+
authenticates the user against the database specified in ``authSource``.
60+
For more information about the ``authSource`` connection option, see
61+
:ref:`pymongo-auth`.
62+
63+
* - ``host[:port]``
64+
65+
- Required. The host and optional port number where MongoDB is running. If you don't
66+
include the port number, the driver uses the default port, ``27017``.
67+
68+
* - ``/defaultauthdb``
69+
70+
- Optional. The authentication database to use if the
71+
connection string includes ``username:password@``
72+
authentication credentials but not the ``authSource`` option. If you don't include
73+
this component, the client authenticates the user against the ``admin`` database.
74+
75+
* - ``?<options>``
76+
77+
- Optional. A query string that specifies connection-specific
78+
options as ``<name>=<value>`` pairs. See
79+
:ref:`kotlin-sync-connection-options` for a full description of
80+
these options.
81+
82+
.. Is there relevant connection string content for kotlin sync to ref to? Only see for java sync.
83+
84+
For more information about creating a connection string, see
85+
:manual:`Connection Strings </reference/connection-string?tck=docs_driver_kotlin>` in the
86+
MongoDB Server documentation.
87+
88+
Atlas Connection Example
89+
------------------------
90+
91+
To connect to a MongoDB deployment on Atlas, create a client. You can create a
92+
client that uses your connection string and other client options by passing a
93+
``MongoClientSettings`` object to the ``MongoClient.create()`` method.
94+
95+
To instantiate a ``MongoClientSettings`` object, use the builder method to
96+
specify your connection string and any other client options, and then call
97+
the ``build()`` method. Chain the ``applyConnectionString()``` method to the
98+
builder to specify your connection URI.
99+
100+
You can set the Stable API version client option to avoid breaking changes when
101+
you upgrade to a new server version. To learn more about the Stable API feature,
102+
see the :ref:`Stable API page <kotlin-sync-stable-api>`.
103+
104+
The following code shows how you can specify the connection string and the
105+
Stable API client option when connecting to a MongoDB deployment on Atlas
106+
and verify that the connection is successful:
107+
108+
.. literalinclude:: /includes/connect/mongoclient.kt
109+
:start-after: start-connect-to-atlas
110+
:end-before: end-connect-to-atlas
111+
:language: kotlin
112+
:copyable:
113+
:dedent:
114+
115+
Other Ways to Connect to MongoDB
116+
--------------------------------
117+
118+
If you are connecting to a single MongoDB server instance or replica set that
119+
is not hosted on Atlas, see the following sections to find out how to connect.
120+
121+
.. _connect-local-kotlin-sync-driver:
122+
123+
Connect to a MongoDB Server on Your Local Machine
124+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
125+
126+
If you need to run a MongoDB server on your local machine for development
127+
purposes instead of using an Atlas cluster, you need to complete the following:
128+
129+
1. Download the `Community <https://www.mongodb.com/try/download/community>`__
130+
or `Enterprise <https://www.mongodb.com/try/download/enterprise>`__ version
131+
of MongoDB Server.
132+
133+
#. :ref:`Install and configure <tutorials-installation>`
134+
MongoDB Server.
135+
136+
#. Start the server.
137+
138+
.. important::
139+
140+
Always secure your MongoDB server from malicious attacks. See our
141+
:manual:`Security Checklist </administration/security-checklist/>` for a
142+
list of security recommendations.
143+
144+
After you successfully start your MongoDB server, specify your connection
145+
string in your driver connection code.
146+
147+
If your MongoDB Server is running locally, you can use the connection string
148+
``"mongodb://localhost:<port>"`` where ``<port>`` is the port number you
149+
configured your server to listen for incoming connections. If the port number
150+
is not specified, the default port ``27017`` is used.
151+
152+
If you need to specify a different hostname or IP address, see our Server
153+
Manual entry on :manual:`Connection Strings </reference/connection-string/>`.
154+
155+
.. _connect-replica-set:
156+
157+
Connect to a Replica Set
158+
~~~~~~~~~~~~~~~~~~~~~~~~
159+
160+
A MongoDB replica set deployment is a group of connected instances that
161+
store the same set of data. This configuration of instances provides data
162+
redundancy and high data availability.
163+
164+
To connect to a replica set deployment, specify the hostnames (or IP
165+
addresses) and port numbers of the members of the replica set.
166+
167+
If you are not able to provide a full list of hosts in the replica set,
168+
you can specify a single or subset of the hosts in the replica and
169+
instruct the driver to perform automatic discovery in one of the following
170+
ways:
171+
172+
- Specify the name of the replica set as the value of the ``replicaSet``
173+
parameter
174+
- Specify ``false`` as the value of the ``directConnection`` parameter
175+
- Specify more than one host in the replica set
176+
177+
.. tip::
178+
179+
Although you can specify a subset of the hosts in a replica set,
180+
include all the hosts in the replica set to ensure the driver is able to
181+
establish the connection if one of the hosts are unreachable.
182+
183+
.. _mongo-client-settings-multiple-hosts:
184+
185+
The following examples show how to specify multiple hosts to a ``MongoClient``
186+
instance using either the ``ConnectionString`` or ``MongoClientSettings``
187+
class. Select the tab that corresponds to your preferred class.
188+
189+
.. tabs::
190+
191+
.. tab:: ConnectionString
192+
:tabid: connectionstring
193+
194+
.. literalinclude:: /includes/connect/mongoclient.kt
195+
:start-after: start-replica-set-connection-string
196+
:end-before: end-replica-set-connection-string
197+
:language: kotlin
198+
:copyable:
199+
:dedent:
200+
201+
202+
.. tab:: MongoClientSettings
203+
:tabid: mongoclientsettings
204+
.. literalinclude:: /includes/connect/mongoclient.kt
205+
:start-after: start-replica-set-client-settings
206+
:end-before: end-replica-set-client-settings
207+
:language: kotlin
208+
:copyable:
209+
:dedent:
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import com.mongodb.*
2+
import com.mongodb.kotlin.client.MongoClient
3+
import org.bson.BsonInt64
4+
import org.bson.Document
5+
6+
fun main() {
7+
8+
9+
// start-connect-to-atlas
10+
// Replace the placeholder with your Atlas connection string
11+
val uri = "<connection string>"
12+
13+
// Construct a ServerApi instance using the ServerApi.builder() method
14+
val serverApi = ServerApi.builder()
15+
.version(ServerApiVersion.V1)
16+
.build()
17+
val settings = MongoClientSettings.builder()
18+
.applyConnectionString(ConnectionString(uri))
19+
.serverApi(serverApi)
20+
.build()
21+
22+
// Create a new client and connect to the server
23+
val mongoClient = MongoClient.create(settings)
24+
val database = mongoClient.getDatabase("sample_mflix")
25+
26+
try {
27+
// Send a ping to confirm a successful connection
28+
val command = Document("ping", BsonInt64(1))
29+
val commandResult = database.runCommand(command)
30+
println("Pinged your deployment. You successfully connected to MongoDB!")
31+
} catch (me: MongoException) {
32+
System.err.println(me)
33+
}
34+
// end-connect-to-atlas
35+
36+
// Replication set connection options
37+
38+
// Using ConnectionString class
39+
// start-replica-set-connection-string
40+
val connectionString = ConnectionString("mongodb://host1:27017,host2:27017,host3:27017/")
41+
val mongoClient = MongoClient.create(connectionString)
42+
// end-replica-set-connection-string
43+
44+
// Using MongoClientSettings class
45+
// start-replica-set-client-settings
46+
val seed1 = ServerAddress("host1", 27017)
47+
val seed2 = ServerAddress("host2", 27017)
48+
val seed3 = ServerAddress("host3", 27017)
49+
val settings = MongoClientSettings.builder()
50+
.applyToClusterSettings { builder ->
51+
builder.hosts(
52+
listOf(seed1, seed2, seed3)
53+
)
54+
}
55+
.build()
56+
val mongoClient = MongoClient.create(settings)
57+
// end-replica-set-client-settings
58+
}

0 commit comments

Comments
 (0)