Skip to content

Commit bb65cd9

Browse files
committed
Updates to the getting started quick tour
Including the Async Driver Quick Tour JAVA-1701 JAVA-1702
1 parent ebe5a52 commit bb65cd9

File tree

12 files changed

+1225
-30
lines changed

12 files changed

+1225
-30
lines changed
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
+++
2+
date = "2015-03-17T15:36:56Z"
3+
title = "Async Admin Quick Tour"
4+
[menu.main]
5+
parent = "Getting Started"
6+
weight = 50
7+
pre = "<i class='fa'></i>"
8+
+++
9+
10+
# MongoDB Driver Admin Quick Tour
11+
12+
This is the second part of the MongoDB driver quick tour. In the
13+
[quick tour]({{< relref "getting-started/async-quick-tour.md" >}}) we looked at how to
14+
use the Async Java driver to execute basic CRUD operations. In this section we'll look at some of the
15+
administrative features available in the driver.
16+
17+
The following code snippets come from the `QuickTourAdmin.java` example code
18+
that can be found with the [driver
19+
source]({{< srcref "driver-async/src/examples/tour/QuickTourAdmin.java">}}).
20+
21+
{{% note %}}
22+
See the [installation guide]({{< relref "getting-started/installation-guide.md" >}})
23+
for instructions on how to install the MongoDB Driver.
24+
{{% /note %}}
25+
26+
## Setup
27+
28+
To get use started we'll quickly connect and create a `mongoClient`, `database` and `collection`
29+
variable for use in the examples below:
30+
31+
```java
32+
MongoClient mongoClient = new MongoClient(new ConnectionString("mongodb://localhost"));
33+
MongoDatabase database = mongoClient.getDatabase("mydb");
34+
MongoCollection<Document> collection = database.getCollection("test");
35+
```
36+
37+
{{% note %}}
38+
Sometimes you will need the same or similar callbacks more than once. In these situations
39+
it makes sense to DRY (Do not Repeat Yourself) up your code and save the callback either
40+
as a concrete class or assign to a variable as below:
41+
42+
```java
43+
SingleResultCallback<Void> callbackWhenFinished = new SingleResultCallback<Void>() {
44+
@Override
45+
public void onResult(final Void result, final Throwable t) {
46+
System.out.println("Operation Finished!");
47+
}
48+
};
49+
```
50+
{{% /note %}}
51+
52+
53+
## Get A List of Databases
54+
55+
You can get a list of the available databases:
56+
57+
```java
58+
mongoClient.listDatabaseNames().forEach(new Block<String>() {
59+
@Override
60+
public void apply(final String s) {
61+
System.out.println(s);
62+
}
63+
}, callbackWhenFinished);
64+
```
65+
66+
Calling the `getDatabase()` on `MongoClient` does not create a database.
67+
Only when a database is written to will a database be created. Examples
68+
would be creating an index or collection or inserting a document into a
69+
collection.
70+
71+
## Drop A Database
72+
73+
You can drop a database by name using a `MongoClient` instance:
74+
75+
```java
76+
mongoClient.getDatabase("databaseToBeDropped").drop(callbackWhenFinished);
77+
```
78+
79+
## Create A Collection
80+
81+
Collections in MongoDB are created automatically simply by inserted a document into it. Using the `[createCollection]({{< apiref "com/mongodb/async/client/MongoDatabase.html#createCollection-java.lang.String-com.mongodb.async.SingleResultCallback-">}})` method, you can also create a collection explicitly in order to to customize its configuration. For example, to create a capped collection sized to 1 megabyte:
82+
83+
```java
84+
database.createCollection("cappedCollection",
85+
new CreateCollectionOptions().capped(true).sizeInBytes(0x100000),
86+
callbackWhenFinished);
87+
```
88+
89+
## Get A List of Collections
90+
91+
You can get a list of the available collections in a database:
92+
93+
```java
94+
database.listCollectionNames().forEach(new Block<String>() {
95+
@Override
96+
public void apply(final String databaseName) {
97+
System.out.println(databaseName);
98+
}
99+
}, callbackWhenFinished);
100+
```
101+
102+
## Drop A Collection
103+
104+
You can drop a collection by using the drop() method:
105+
106+
```java
107+
collection.drop(callbackWhenFinished);
108+
```
109+
110+
## Create An Index
111+
112+
MongoDB supports secondary indexes. To create an index, you just
113+
specify the field or combination of fields, and for each field specify the direction of the index for that field.
114+
For `1` ascending or `-1` for descending. The following creates an ascending index on the `i` field:
115+
116+
```java
117+
// create an ascending index on the "i" field
118+
collection.createIndex(new Document("i", 1), callbackWhenFinished);
119+
```
120+
121+
## Get a List of Indexes on a Collection
122+
123+
Use the `listIndexes()` method to get a list of indexes. The following creates a
124+
`printDocumentBlock` Block that prints out the Json version of a document and then passes
125+
that block to the `forEach` method on a
126+
[`mongoIterable`]({{< apiref "com/mongodb/async/client/MongoIterable.html">}})
127+
so that it will printout all the indexes on the collection `test`:
128+
129+
```java
130+
Block<Document> printDocumentBlock = new Block<Document>() {
131+
@Override
132+
public void apply(final Document document) {
133+
System.out.println(document.toJson());
134+
}
135+
};
136+
137+
collection.listIndexes().forEach(printDocumentBlock, callbackWhenFinished);
138+
```
139+
140+
The example should print the following indexes:
141+
142+
```json
143+
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.test" }
144+
{ "v" : 1, "key" : { "i" : 1 }, "name" : "i_1", "ns" : "mydb.test" }
145+
Operation Finished!
146+
```
147+
148+
## Text indexes
149+
150+
MongoDB also provides text indexes to support text search of string
151+
content. Text indexes can include any field whose value is a string or
152+
an array of string elements. To create a text index specify the string
153+
literal "text" in the index document:
154+
155+
```java
156+
// create a text index on the "content" field
157+
coll.createIndex(new Document("content", "text"), callbackWhenFinished);
158+
```
159+
160+
As of MongoDB 2.6, text indexes are now integrated into the main query
161+
language and enabled by default (here we use the [`Filters.text`]({{< apiref "com/mongodb/client/model/Filters.html#text-java.lang.String-">}}) helper):
162+
163+
```java
164+
// Insert some documents
165+
collection.insertOne(new Document("_id", 0).append("content", "textual content"), callbackWhenFinished);
166+
collection.insertOne(new Document("_id", 1).append("content", "additional content"), callbackWhenFinished);
167+
collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"), callbackWhenFinished);
168+
169+
// Find using the text index
170+
long matchCount = collection.count(text("textual content -irrelevant"));
171+
System.out.println("Text search matches: " + matchCount);
172+
173+
// Find using the $language operator
174+
Bson textSearch = text("textual content -irrelevant", "english");
175+
matchCount = collection.count(textSearch);
176+
System.out.println("Text search matches (english): " + matchCount);
177+
178+
// Find the highest scoring match
179+
// Find using the text index
180+
collection.count(text("textual content -irrelevant"), new SingleResultCallback<Long>() {
181+
@Override
182+
public void onResult(final Long matchCount, final Throwable t) {
183+
System.out.println("Text search matches: " + matchCount);
184+
}
185+
});
186+
187+
188+
// Find using the $language operator
189+
Bson textSearch = text("textual content -irrelevant", "english");
190+
collection.count(textSearch, new SingleResultCallback<Long>() {
191+
@Override
192+
public void onResult(final Long matchCount, final Throwable t) {
193+
System.out.println("Text search matches (english): " + matchCount);
194+
}
195+
});
196+
197+
// Find the highest scoring match
198+
Document projection = new Document("score", new Document("$meta", "textScore"));
199+
collection.find(textSearch).projection(projection).first(new SingleResultCallback<Document>() {
200+
@Override
201+
public void onResult(final Document highest, final Throwable t) {
202+
System.out.println("Highest scoring document: " + highest.toJson());
203+
204+
}
205+
});
206+
```
207+
208+
and it should print:
209+
210+
```json
211+
Text search matches: 2
212+
Text search matches (english): 2
213+
Highest scoring document: { "_id" : 1, "content" : "additional content", "score" : 0.75 }
214+
```
215+
216+
For more information about text search see the [text index]({{< docsref "/core/index-text" >}}) and
217+
[$text query operator]({{< docsref "/reference/operator/query/text">}}) documentation.
218+
219+
## Running a command
220+
221+
Not all commands have a specific helper, however you can run any [command]({{< docsref "/reference/command">}})
222+
by using the [`runCommand()`](http://api.mongodb.org/java/3.0/?com/mongodb/async/client/MongoDatabase.html#runCommand-org.bson.conversions.Bson-com.mongodb.ReadPreference-com.mongodb.async.SingleResultCallback-) method. Here we call the [buildInfo]({{ docsref "reference/command/buildInfo" }}) command:
223+
224+
```java
225+
database.runCommand(new Document("buildInfo", 1), new SingleResultCallback<Document>() {
226+
@Override
227+
public void onResult(final Document buildInfo, final Throwable t) {
228+
System.out.println(buildInfo);
229+
}
230+
});
231+
```

0 commit comments

Comments
 (0)