Skip to content

Commit 9cccd84

Browse files
authored
DOCSP-38219: db and coll (#11)
* DOCSP-38219: db and coll (cherry picked from commit 17daca3a0144bf60647e838794a913ebd7b21eb7) * CC PR fixes
1 parent beba6e9 commit 9cccd84

File tree

2 files changed

+280
-2
lines changed

2 files changed

+280
-2
lines changed

source/tutorials.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ Tutorials
77
.. toctree::
88

99
/tutorials/connect/
10+
/tutorials/db-coll/
1011

1112
..
12-
/tutorials/db-coll/
1313
/tutorials/indexes/
1414
/tutorials/read-ops/
1515
/tutorials/encrypt/
@@ -22,9 +22,9 @@ Tutorials
2222
/tutorials/command/
2323

2424
- :ref:`scala-connect`
25+
- :ref:`scala-db-coll`
2526

2627
..
27-
- :ref:`javars-db-coll`
2828
- :ref:`javars-indexes`
2929
- :ref:`javars-read-operations`
3030
- :ref:`javars-encrypt`

source/tutorials/db-coll.txt

Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
.. _scala-db-coll:
2+
3+
=========================
4+
Databases and Collections
5+
=========================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: code example, validation, codec registry, write concern
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 1
18+
:class: singlecol
19+
20+
MongoDB organizes data in a hierarchical structure. A MongoDB deployment
21+
contains one or more databases, and each database contains one or more
22+
collections. In each collection, MongoDB stores data as documents that
23+
contain field-and-value pairs.
24+
25+
Prerequisites
26+
-------------
27+
28+
You must include the following import statements in your program to run the
29+
code examples in this guide:
30+
31+
.. code-block:: scala
32+
33+
import org.mongodb.scala._
34+
import org.mongodb.scala.model.Filters._
35+
36+
.. include:: /includes/obs-note.rst
37+
38+
Connect to a MongoDB Deployment
39+
-------------------------------
40+
41+
First, connect to a running MongoDB deployment.
42+
43+
The following code connects to a standalone MongoDB deployment running
44+
on ``localhost`` on port ``27017``:
45+
46+
.. code-block:: scala
47+
48+
val mongoClient = MongoClient()
49+
50+
To learn more about connecting to MongoDB deployments,
51+
see the :ref:`scala-connect` tutorial.
52+
53+
Access a Database
54+
-----------------
55+
56+
Once you have a ``MongoClient`` instance connected to a MongoDB
57+
deployment, use the ```getDatabase()`` method to access a database.
58+
59+
Pass the name of the database as a parameter to the ``getDatabase()``
60+
method. If a database does not exist, MongoDB creates it when
61+
you insert any data into the database.
62+
63+
The following example accesses the ``test`` database:
64+
65+
.. code-block:: scala
66+
67+
val database: MongoDatabase = mongoClient.getDatabase("test")
68+
69+
.. note::
70+
71+
``MongoDatabase`` instances are immutable. To learn more, see the
72+
:ref:`Immutability <scala-immutability>` section of this guide.
73+
74+
Access a Collection
75+
-------------------
76+
77+
After you create a ``MongoDatabase`` instance, use the
78+
``getCollection()`` method to access a collection from within that
79+
database.
80+
81+
Pass the name of the collection as a parameter to the ``getCollection()``
82+
method.
83+
84+
Using the ``database`` instance created in the preceding section, the
85+
following code accesses the collection named ``myTestCollection``:
86+
87+
.. code-block:: scala
88+
89+
val coll: MongoCollection[Document] = database.getCollection("myTestCollection")
90+
91+
.. note::
92+
93+
``MongoCollection`` instances are immutable. To learn more, see the
94+
:ref:`Immutability <scala-immutability>` section of this guide.
95+
96+
If a collection with that name does not exist, MongoDB creates it when
97+
you first insert data into that collection.
98+
99+
You can also directly create a collection with various options, such
100+
as setting the maximum size or creating documentation validation rules.
101+
102+
Create a Collection
103+
-------------------
104+
105+
The driver provides the ``createCollection()`` method to
106+
directly create a collection. When you create a
107+
collection, you can specify various collection options, such as a
108+
maximum size or documentation validation rules, with the
109+
``CreateCollectionOptions`` class.
110+
111+
If you are not specifying any options, you do not need to directly
112+
create the collection since MongoDB automatically creates new
113+
collections when you first insert data.
114+
115+
Capped Collection
116+
~~~~~~~~~~~~~~~~~
117+
118+
The following operation creates a capped collection limited to 1
119+
megabyte:
120+
121+
.. code-block:: scala
122+
123+
database.createCollection("cappedCollection", CreateCollectionOptions().capped(true).sizeInBytes(0x100000))
124+
.printResults()
125+
126+
To learn more about capped collections, see :manual:`Capped Collections
127+
</core/capped-collections/>` in the Server manual.
128+
129+
Document Validation
130+
~~~~~~~~~~~~~~~~~~~
131+
132+
MongoDB allows you to validate documents during
133+
updates and inserts. Validation rules are specified on a collection
134+
level by using the ``ValidationOptions`` class, which takes a
135+
filter document that specifies the validation rules or expressions.
136+
137+
The following example creates a collection with schema validation:
138+
139+
.. code-block:: scala
140+
141+
ValidationOptions collOptions = ValidationOptions().validator(
142+
Filters.or(Filters.exists("email"), Filters.exists("phone")))
143+
144+
database.createCollection("contacts", CreateCollectionOptions().validationOptions(collOptions))
145+
.printResults()
146+
147+
To learn more about document validation, see :manual:`Schema Validation
148+
</core/schema-validation/>` in the Server manual.
149+
150+
Get A List of Collections
151+
-------------------------
152+
153+
You can get a list of the collections in a database by using the
154+
``MongoDatabase.listCollectionNames()`` method:
155+
156+
.. code-block:: scala
157+
158+
database.listCollectionNames().printResults()
159+
160+
Drop a Collection
161+
-----------------
162+
163+
You can drop a collection and delete all of the data in the collection
164+
by using the ``MongoCollection.drop()`` method:
165+
166+
.. code-block:: scala
167+
168+
val collection: MongoCollection[Document] = database.getCollection("contacts")
169+
collection.drop().printResults()
170+
171+
.. _scala-immutability:
172+
173+
Immutability
174+
------------
175+
176+
``MongoDatabase`` and ``MongoCollection`` instances are immutable. To
177+
create new instances from existing instances that have different
178+
properties, such as different :manual:`read concerns
179+
</reference/read-concern/>`, :manual:`read preferences
180+
</reference/read-preference/>`, and :manual:`write concerns
181+
</reference/write-concern/>`, the ``MongoDatabase`` and
182+
``MongoCollection`` class provides the following methods:
183+
184+
- ``MongoDatabase.withReadConcern()``
185+
- ``MongoDatabase.withReadPreference()``
186+
- ``MongoDatabase.withWriteConcern()``
187+
- ``MongoCollection.withReadConcern()``
188+
- ``MongoCollection.withReadPreference()``
189+
- ``MongoCollection.withWriteConcern()``
190+
191+
.. TODO To learn more, see the :ref:`scala-read-operations` and
192+
.. :ref:`scala-write-ops` tutorials.
193+
194+
CodecRegistry
195+
-------------
196+
197+
An overload of the ``getCollection()`` method allows you to specify a
198+
different class for representing BSON documents. For example, you
199+
might want to use the strict and type-safe ``BsonDocument`` class to
200+
model your documents when performing CRUD operations:
201+
202+
.. code-block:: scala
203+
204+
import org.mongodb.scala.bson._
205+
206+
val collection: MongoCollection[BsonDocument] = database.getCollection[BsonDocument]("mycoll")
207+
208+
// insert a document
209+
val document = BsonDocument("{x: 1}")
210+
collection.insertOne(document).printResults()
211+
212+
document.append("x", BsonInt32(2)).append("y", BsonInt32(3))
213+
214+
// replace a document
215+
collection.replaceOne(Filters.equal("_id", document.get("_id")), document)
216+
.printResults()
217+
218+
// find documents
219+
collection.find().printResults()
220+
221+
There are two requirements that any class must meet to be used in
222+
this way:
223+
224+
- ``Codec`` instance for the class must be registered in the
225+
``CodecRegistry`` for the ``MongoCollection``.
226+
227+
- ``Codec`` instance must be one that encodes and decodes a full BSON
228+
document, and not just, for example, a single BSON value like an
229+
``Int32``.
230+
231+
By default, a ``MongoCollection`` is configured with ``Codec`` instances
232+
for four classes:
233+
234+
- ``Document`` (Scala ``BsonDocument`` wrapper)
235+
- ``BsonDocument``
236+
- ``Document`` (Java driver's loosely typed ``Document`` class)
237+
- ``BasicDBObject``
238+
239+
Applications are free to register ``Codec`` implementations
240+
for other classes by customizing the ``CodecRegistry``. New
241+
``CodecRegistry`` instances are configurable at the following levels:
242+
243+
- In a ``MongoClient`` within ``MongoClientSettings``
244+
- In a ``MongoDatabase`` within its ``withCodecRegistry`` method
245+
- In a ``MongoCollection`` within its ``withCodecRegistry`` method
246+
247+
Consider the case of encoding and decoding instances of the ``UUID``
248+
class. The driver by default encodes instances of ``UUID`` by using a
249+
byte ordering that is not compatible with other MongoDB drivers, and
250+
changing the default would be dangerous.
251+
252+
It is possible for new applications that require interoperability across
253+
multiple drivers to be able to change that default, and they can do that
254+
by specifying a ``CodecRegistry``
255+
256+
.. code-block:: scala
257+
258+
// replaces the default UuidCodec with one that uses the new standard UUID representation
259+
import org.bson.UuidRepresentation
260+
import org.bson.codecs.UuidCodec
261+
import org.bson.codecs.configuration.CodecRegistries
262+
263+
val codecRegistry = CodecRegistries.fromRegistries(
264+
CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)),
265+
MongoClient.DEFAULT_CODEC_REGISTRY)
266+
267+
// globally
268+
val settings = MongoClientSettings.builder()
269+
.codecRegistry(codecRegistry).build()
270+
val client = MongoClient(settings)
271+
272+
// or at the database level
273+
val database = client.getDatabase("mydb")
274+
.withCodecRegistry(codecRegistry)
275+
276+
// or at the collection level
277+
val collection = database.getCollection("mycoll")
278+
.withCodecRegistry(codecRegistry)

0 commit comments

Comments
 (0)