Skip to content

Commit 9fb72e9

Browse files
committed
Docs: Added a POJO based quick start
JAVA-2503
1 parent 23bdc90 commit 9fb72e9

File tree

13 files changed

+1609
-424
lines changed

13 files changed

+1609
-424
lines changed
Lines changed: 331 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,331 @@
1+
+++
2+
date = "2017-05-17T15:36:57Z"
3+
title = "Quick Start - POJOs"
4+
[menu.main]
5+
parent = "MongoDB Async Driver"
6+
identifier = "Async Quick Start - POJOs"
7+
weight = 15
8+
pre = "<i class='fa'></i>"
9+
+++
10+
11+
# MongoDB Async Driver Quick Start - POJOs
12+
13+
{{% note %}}
14+
POJOs stands for Plain Old Java Objects.
15+
16+
The following code snippets come from the [`PojoQuickTour.java`]({{< srcref "driver-async/src/examples/tour/PojoQuickTour.java">}}) example code
17+
that can be found with the driver source on github.
18+
{{% /note %}}
19+
20+
## Prerequisites
21+
22+
- A running MongoDB on localhost using the default port for MongoDB `27017`
23+
24+
- MongoDB Driver. See [Installation]({{< relref "driver/getting-started/installation.md" >}}) for instructions on how to install the MongoDB driver.
25+
26+
- Quick Start. This guide follows on from the [Quick Start]({{< relref "driver/getting-started/quick-start.md" >}}).
27+
28+
- The following import statements:
29+
30+
```java
31+
import com.mongodb.Block;
32+
import com.mongodb.async.SingleResultCallback;
33+
import com.mongodb.async.client.MongoClient;
34+
import com.mongodb.async.client.MongoClients;
35+
import com.mongodb.async.client.MongoCollection;
36+
import com.mongodb.async.client.MongoDatabase;
37+
import com.mongodb.client.result.DeleteResult;
38+
import com.mongodb.client.result.UpdateResult;
39+
import org.bson.codecs.configuration.CodecRegistry;
40+
import org.bson.codecs.pojo.PojoCodecProvider;
41+
42+
import java.util.List;
43+
44+
import static com.mongodb.client.model.Filters.*;
45+
import static com.mongodb.client.model.Updates.*;
46+
import static java.util.Arrays.asList;
47+
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
48+
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
49+
```
50+
51+
- The following POJO classes. The full source is available on github for the [Person]({{< srcref "driver-async/src/examples/tour/Person.java">}}) and [Address]({{< srcref "driver-async/src/examples/tour/Address.java">}})
52+
POJOs. Here are the main implementation details:
53+
54+
```java
55+
public final class Person {
56+
ObjectId id;
57+
String name;
58+
int age;
59+
Address address;
60+
61+
public Person() {
62+
}
63+
64+
// Rest of implementation
65+
}
66+
67+
public final class Address {
68+
String street;
69+
String city;
70+
String zip;
71+
72+
public Address() {
73+
}
74+
75+
// Rest of implementation
76+
}
77+
```
78+
79+
## Creating a Custom CodecRegistry
80+
81+
Before you can use a POJO with the driver, you need to configure the [`CodecRegistry` ]({{< relref "bson/codecs.md" >}}) to include a codecs
82+
to handle the translation to and from [`bson`]({{< relref "bson/index.md" >}}) for your POJOs. The simplest way to do that is to use the
83+
[`PojoCodecProvider.builder()`]({{< apiref "org/bson/codecs/pojo/PojoCodecProvider.html">}}) to create and configure a `CodecProvider`.
84+
85+
The following example will combine a codec registry for the `Person` and `Address` POJOs, with the default codec registry:
86+
```java
87+
CodecRegistry pojoCodecRegistry = fromRegistries(
88+
fromProviders(PojoCodecProvider.builder().register(Person.class, Address.class).build()),
89+
MongoClient.getDefaultCodecRegistry());
90+
```
91+
92+
### Using the CodecRegistry
93+
94+
There are multiple ways to set the `pojoCodecRegistry` for use:
95+
96+
- You can set it when instantiating a MongoClient object:
97+
98+
```java
99+
MongoClient mongoClient = new MongoClient("localhost", MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
100+
```
101+
102+
- You can use an alternative `CodecRegistry` with a `MongoDatabase`:
103+
104+
```java
105+
database = database.withCodecRegistry(pojoCodecRegistry);
106+
```
107+
108+
- You can use an alternative `CodecRegistry` with a `MongoCollection`:
109+
110+
```java
111+
collection = collection.withCodecRegistry(pojoCodecRegistry);
112+
```
113+
114+
## Inserting a POJO into MongoDB
115+
116+
Before you can insert a POJO into MongoDB, you need a `MongoCollection` instance configured with the Pojo's type:
117+
118+
```java
119+
MongoCollection<Person> collection = database.getCollection("people", Person.class);
120+
```
121+
122+
### Insert a Person
123+
{{% note class="important" %}}
124+
Remember, always check for errors in any `SingleResultCallback<T>` implementation and handle them appropriately.
125+
126+
For sake of brevity, this tutorial omits the error check logic in the code examples.
127+
{{% /note %}}
128+
129+
To insert a Person into the collection, you can use the collection's [`insertOne()`]({{< apiref "com/mongodb/client/MongoCollection.html#insertOne-TDocument-" >}}) method.
130+
131+
```java
132+
Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
133+
collection.insertOne(ada, new SingleResultCallback<Void>() {
134+
@Override
135+
public void onResult(final Void result, final Throwable t) {
136+
System.out.println("Inserted!");
137+
}
138+
});
139+
```
140+
141+
### Insert Many Persons
142+
143+
To add multiple Person instances, you can use the collection's [`insertMany()`]({{< apiref "com/mongodb/client/MongoCollection.html#insertMany-java.util.List-" >}}) method
144+
which takes a list of `Person`.
145+
146+
The following example will add multiple Person instances into the collection:
147+
148+
```java
149+
List<Person> people = asList(
150+
new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")),
151+
new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")),
152+
new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null))
153+
);
154+
155+
collection.insertMany(people, new SingleResultCallback<Void>() {
156+
@Override
157+
public void onResult(final Void result, final Throwable t) {
158+
collection.count(new SingleResultCallback<Long>() {
159+
@Override
160+
public void onResult(final Long count, final Throwable t) {
161+
System.out.println("total # of people " + count);
162+
}
163+
});
164+
}
165+
});
166+
```
167+
168+
## Query the Collection
169+
170+
To query the collection, you can use the collection's [`find()`]({{< apiref "com/mongodb/client/MongoCollection.html#find--">}}) method.
171+
172+
The following example prints all the Person instances in the collection:
173+
```java
174+
Block<Person> printBlock = new Block<Person>() {
175+
@Override
176+
public void apply(final Person person) {
177+
System.out.println(person);
178+
}
179+
};
180+
181+
SingleResultCallback<Void> callbackWhenFinished = new SingleResultCallback<Void>() {
182+
@Override
183+
public void onResult(final Void result, final Throwable t) {
184+
System.out.println("Operation Finished!");
185+
}
186+
};
187+
188+
collection.find().forEach(printBlock, callbackWhenFinished);
189+
```
190+
191+
The example uses the [`forEach`]({{ <apiref "com/mongodb/client/MongoIterable.html#forEach-com.mongodb.Block-">}}) method on the ``FindIterable``
192+
object to apply a block to each Person and outputs the following:
193+
194+
```bash
195+
Person{id='591dbc2550852fa685b3ad17', name='Ada Byron', age=20, address=Address{street='St James Square', city='London', zip='W1'}}
196+
Person{id='591dbc2550852fa685b3ad18', name='Charles Babbage', age=45, address=Address{street='5 Devonshire Street', city='London', zip='W11'}}
197+
Person{id='591dbc2550852fa685b3ad19', name='Alan Turing', age=28, address=Address{street='Bletchley Hall', city='Bletchley Park', zip='MK12'}}
198+
Person{id='591dbc2550852fa685b3ad1a', name='Timothy Berners-Lee', age=61, address=Address{street='Colehill', city='Wimborne', zip='null'}}
199+
```
200+
201+
## Specify a Query Filter
202+
203+
To query for Person instance that match certain conditions, pass a filter object to the [`find()`]({{< apiref "com/mongodb/client/MongoCollection.html#find--">}}) method.
204+
To facilitate creating filter objects, Java driver provides the [`Filters`]({{< apiref "com/mongodb/client/model/Filters.html">}}) helper.
205+
206+
{{% note class="important" %}}
207+
When querying POJOs you *must* query against the document field name and not the Pojo's field name.
208+
By default they are the same but it is possible to change how POJO field names are mapped.
209+
{{% /note %}}
210+
211+
212+
### Get A Single Person That Matches a Filter
213+
214+
For example, to find the first `Person` in the database that lives in `Wimborne` pass an [`eq`]({{<apiref "com/mongodb/client/model/Filters.html#eq-java.lang.String-TItem-">}})
215+
filter object to specify the equality condition:
216+
217+
```java
218+
SingleResultCallback<Person> printCallback = new SingleResultCallback<Person>() {
219+
@Override
220+
public void onResult(final Person person, final Throwable t) {
221+
System.out.println(person);
222+
}
223+
};
224+
collection.find(eq("address.city", "Wimborne")).first(printCallback);
225+
```
226+
The example prints one document:
227+
228+
```bash
229+
Person{id='591dbc2550852fa685b3ad1a', name='Timothy Berners-Lee', age=61,
230+
address=Address{street='Colehill', city='Wimborne', zip='null'}}
231+
```
232+
233+
### Get All Person Instances That Match a Filter
234+
235+
The following example returns and prints everyone where ``"age" > 30``:
236+
237+
```java
238+
collection.find(gt("age", 30)).forEach(printBlock, callbackWhenFinished);
239+
```
240+
241+
## Update Documents
242+
243+
To update documents in a collection, you can use the collection's [`updateOne`]({{<apiref "com/mongodb/client/MongoCollection.html#updateOne-org.bson.conversions.Bson-org.bson.conversions.Bson-">}}) and [`updateMany`]({{<apiref "com/mongodb/async/client/MongoCollection.html#updateMany-org.bson.conversions.Bson-org.bson.conversions.Bson-">}}) methods.
244+
245+
Pass to the methods:
246+
247+
- A filter object to determine the document or documents to update. To facilitate creating filter objects, Java driver provides the [`Filters`]({{< apiref "com/mongodb/client/model/Filters.html">}}) helper. To specify an empty filter (i.e. match all Persons in a collection), use an empty [`Document`]({{< apiref "org/bson/Document.html" >}}) object.
248+
249+
- An update document that specifies the modifications. For a list of the available operators, see [update operators]({{<docsref "reference/operator/update-field">}}).
250+
251+
The update methods return an [`UpdateResult`]({{<apiref "com/mongodb/client/result/UpdateResult.html">}}) which provides information about the operation including the number of documents modified by the update.
252+
253+
### Update a Single Person
254+
255+
To update at most a single `Person`, use the [`updateOne`]({{<apiref "com/mongodb/client/MongoCollection.html#updateOne-org.bson.conversions.Bson-org.bson.conversions.Bson-">}}) method.
256+
257+
The following example updates `Ada Byron` setting their age to `23` and name to `Ada Lovelace`:
258+
259+
```java
260+
SingleResultCallback<UpdateResult> printModifiedCount = new SingleResultCallback<UpdateResult>() {
261+
@Override
262+
public void onResult(final UpdateResult result, final Throwable t) {
263+
System.out.println(result.getModifiedCount());
264+
}
265+
};
266+
collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace")), printModifiedCount);
267+
```
268+
269+
### Update Multiple Persons
270+
271+
To update all Persons that match a filter, use the [`updateMany`]({{<apiref "com/mongodb/async/client/MongoCollection.html#updateMany-org.bson.conversions.Bson-org.bson.conversions.Bson-">}}) method.
272+
273+
The following example sets the zip field to `null` for all documents that have a `zip` value:
274+
275+
```java
276+
collection.updateMany(not(eq("zip", null)), set("zip", null), printModifiedCount);
277+
278+
```
279+
280+
### Replace a Single Person
281+
282+
An alternative method to change an existing `Person`, would be to use the [`replaceOne`]({{<apiref "com/mongodb/client/MongoCollection.html#replaceOne-org.bson.conversions.Bson-TDocument-">}}) method.
283+
284+
The following example replaces the `Ada Lovelace` back to the original document:
285+
286+
```java
287+
collection.replaceOne(eq("name", "Ada Lovelace"), ada, printModifiedCount);
288+
```
289+
290+
## Delete Documents
291+
292+
To delete documents from a collection, you can use the collection's [`deleteOne`]({{< apiref "com/mongodb/client/MongoCollection.html#deleteOne-org.bson.conversions.Bson-">}}) and [`deleteMany`]({{< apiref "com/mongodb/client/MongoCollection.html#deleteMany-org.bson.conversions.Bson-">}}) methods.
293+
294+
Pass to the methods a filter object to determine the document or documents to delete. To facilitate creating filter objects, Java driver provides the [`Filters`]({{< apiref "com/mongodb/client/model/Filters.html">}}) helper. To specify an empty filter (i.e. match all documents in a collection), use an empty [`Document`]({{< apiref "org/bson/Document.html" >}}) object.
295+
296+
The delete methods return a [`DeleteResult`]({{< apiref "com/mongodb/client/result/DeleteResult.html">}})
297+
which provides information about the operation including the number of documents deleted.
298+
299+
### Delete a Single Person That Matches a Filter
300+
301+
To delete at most a single `Person` that matches a filter, use the [`deleteOne`]({{< apiref "com/mongodb/client/MongoCollection.html#deleteOne-org.bson.conversions.Bson-">}}) method:
302+
303+
The following example deletes at most one `Person` who lives in `Wimborne`:
304+
305+
```java
306+
SingleResultCallback<DeleteResult> printDeletedCount = new SingleResultCallback<DeleteResult>() {
307+
@Override
308+
public void onResult(final DeleteResult result, final Throwable t) {
309+
System.out.println(result.getDeletedCount());
310+
}
311+
};
312+
313+
collection.deleteOne(eq("address.city", "Wimborne"), printDeletedCount);
314+
```
315+
316+
### Delete All Persons That Match a Filter
317+
318+
To delete multiple Persons matching a filter use the [`deleteMany`]({{< apiref "com/mongodb/client/MongoCollection.html#deleteMany-org.bson.conversions.Bson-">}}) method.
319+
320+
The following example deletes all Persons that live in `London`:
321+
322+
```java
323+
collection.deleteMany(eq("address.city", "London"), printDeletedCount);
324+
```
325+
326+
### Additional Information
327+
328+
For additional information about the configuring the `PojoCodecProvider`, see the [Bson POJO page]({{< ref "bson/pojos.md" >}}).
329+
330+
For additional tutorials about using MongoDB (such as to use the aggregation framework, specify write concern, etc.), see the [Java Async Driver Tutorials]({{< ref "driver-async/tutorials/index.md" >}}).
331+

docs/reference/content/driver-async/getting-started/quick-start.md

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@ date = "2015-03-17T15:36:56Z"
33
title = "Quick Start"
44
[menu.main]
55
parent = "MongoDB Async Driver"
6-
identifier = "Async Quick Tour"
6+
identifier = "Async Quick Start"
77
weight = 10
88
pre = "<i class='fa'></i>"
99
+++
1010

11-
# MongoDB Async Driver Quick Tour
11+
# MongoDB Async Driver Quick Start
1212

1313
The following code snippets come from the [`QuickTour.java`]({{< srcref "driver-async/src/examples/tour/QuickTour.java">}}) example code
1414
that can be found with the async driver source on github.
@@ -434,3 +434,9 @@ collection.deleteMany(gte("i", 100), new SingleResultCallback<DeleteResult>() {
434434
}
435435
});
436436
```
437+
438+
### Additional Information
439+
440+
For additional tutorials about using MongoDB with POJOs, see the [POJOs Quick Start]({{< ref "driver-async/getting-started/quick-start-pojo.md" >}}).
441+
442+
For additional tutorials (such as to use the aggregation framework, specify write concern, etc.), see the [Java Async Driver Tutorials]({{< ref "driver-async/tutorials/index.md" >}}).

docs/reference/content/driver-async/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ information on breaking changes.
2323

2424
## Getting Started
2525

26-
To get started, see the [Installation Guide]({{< relref "driver-async/getting-started/installation.md" >}}) and the [Quick Start Guide]({{< relref "driver-async/getting-started/quick-start.md" >}}).
26+
To get started, see the [Installation Guide]({{< relref "driver-async/getting-started/installation.md" >}}), the [Quick Start Guide]({{< relref "driver-async/getting-started/quick-start.md" >}}) and the [Quick Start with POJOs Guide]({{< relref "driver-async/getting-started/quick-start-pojo.md" >}})..
2727

2828
## Tutorials
2929

0 commit comments

Comments
 (0)