Skip to content

Commit a39a08d

Browse files
authored
Merge pull request #8 from rustagir/DOCSP-37780-tutorials-db-coll
DOCSP-37780: db collection tutorial
2 parents 1654ab9 + 82dd7bc commit a39a08d

File tree

2 files changed

+277
-0
lines changed

2 files changed

+277
-0
lines changed

source/tutorials.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@ Tutorials
77
.. toctree::
88

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

source/tutorials/db-coll.txt

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

0 commit comments

Comments
 (0)