Skip to content

Commit b08268d

Browse files
committed
Updated the example code
To bring it inline with the tutorial changes refs DOCS-3410
1 parent b808c47 commit b08268d

File tree

3 files changed

+300
-39
lines changed

3 files changed

+300
-39
lines changed
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/*
2+
* Copyright (c) 2008-2014 MongoDB, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package example;
18+
19+
import com.mongodb.AggregationOptions;
20+
import com.mongodb.AggregationOutput;
21+
import com.mongodb.BasicDBObject;
22+
import com.mongodb.BasicDBObjectBuilder;
23+
import com.mongodb.Cursor;
24+
import com.mongodb.DB;
25+
import com.mongodb.DBCollection;
26+
import com.mongodb.DBObject;
27+
import com.mongodb.MongoClient;
28+
29+
import java.net.UnknownHostException;
30+
import java.util.Arrays;
31+
import java.util.List;
32+
33+
/**
34+
* The tutorial from http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
35+
*/
36+
public class AggregationExample {
37+
// CHECKSTYLE:OFF
38+
39+
/**
40+
* Run this main method to see the output of this quick example.
41+
*
42+
* @param args takes no args
43+
* @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
44+
*/
45+
public static void main(final String[] args) throws UnknownHostException {
46+
// connect to the local database server
47+
MongoClient mongoClient = new MongoClient();
48+
49+
// get handle to "mydb"
50+
DB db = mongoClient.getDB("mydb");
51+
52+
// Authenticate - optional
53+
// boolean auth = db.authenticate("foo", "bar");
54+
55+
// Add some sample data
56+
DBCollection coll = db.getCollection("aggregationExample");
57+
coll.insert(new BasicDBObjectBuilder()
58+
.add("employee", 1)
59+
.add("department", "Sales")
60+
.add("amount", 71)
61+
.add("type", "airfare")
62+
.get());
63+
coll.insert(new BasicDBObjectBuilder()
64+
.add("employee", 2)
65+
.add("department", "Engineering")
66+
.add("amount", 15)
67+
.add("type", "airfare")
68+
.get());
69+
coll.insert(new BasicDBObjectBuilder()
70+
.add("employee", 4)
71+
.add("department", "Human Resources")
72+
.add("amount", 5)
73+
.add("type", "airfare")
74+
.get());
75+
coll.insert(new BasicDBObjectBuilder()
76+
.add("employee", 42)
77+
.add("department", "Sales")
78+
.add("amount", 77)
79+
.add("type", "airfare")
80+
.get());
81+
82+
// create our pipeline operations, first with the $match
83+
DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare"));
84+
85+
// build the $projection operation
86+
DBObject fields = new BasicDBObject("department", 1);
87+
fields.put("amount", 1);
88+
fields.put("_id", 0);
89+
DBObject project = new BasicDBObject("$project", fields );
90+
91+
// Now the $group operation
92+
DBObject groupFields = new BasicDBObject( "_id", "$department");
93+
groupFields.put("average", new BasicDBObject( "$avg", "$amount"));
94+
DBObject group = new BasicDBObject("$group", groupFields);
95+
96+
// Finally the $sort operation
97+
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("average", -1));
98+
99+
// run aggregation
100+
List<DBObject> pipeline = Arrays.asList(match, project, group, sort);
101+
AggregationOutput output = coll.aggregate(pipeline);
102+
103+
// Output the results
104+
for (DBObject result : output.results()) {
105+
System.out.println(result);
106+
}
107+
108+
// Aggregation Cursor
109+
AggregationOptions aggregationOptions = AggregationOptions.builder()
110+
.batchSize(100)
111+
.outputMode(AggregationOptions.OutputMode.CURSOR)
112+
.allowDiskUse(true)
113+
.build();
114+
115+
Cursor cursor = coll.aggregate(pipeline, aggregationOptions);
116+
while (cursor.hasNext()) {
117+
System.out.println(cursor.next());
118+
}
119+
120+
// clean up
121+
db.dropDatabase();
122+
mongoClient.close();
123+
}
124+
}

src/examples/example/QuickTour.java

Lines changed: 75 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,24 @@
1717
package example;
1818

1919
import com.mongodb.BasicDBObject;
20+
import com.mongodb.BulkWriteOperation;
21+
import com.mongodb.BulkWriteResult;
22+
import com.mongodb.Cursor;
2023
import com.mongodb.DB;
2124
import com.mongodb.DBCollection;
2225
import com.mongodb.DBCursor;
2326
import com.mongodb.DBObject;
2427
import com.mongodb.MongoClient;
28+
import com.mongodb.ParallelScanOptions;
2529

2630
import java.net.UnknownHostException;
2731
import java.util.List;
2832
import java.util.Set;
2933

34+
import static java.util.concurrent.TimeUnit.SECONDS;
35+
3036
/**
31-
* The tutorial from http://www.mongodb.org/display/DOCS/Java+Tutorial.
37+
* The tutorial from http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
3238
*/
3339
public class QuickTour {
3440
// CHECKSTYLE:OFF
@@ -55,30 +61,31 @@ public static void main(final String[] args) throws UnknownHostException {
5561
}
5662

5763
// get a collection object to work with
58-
DBCollection testCollection = db.getCollection("testCollection");
64+
DBCollection coll = db.getCollection("testCollection");
5965

6066
// drop all the data in it
61-
testCollection.drop();
67+
coll.drop();
6268

6369
// make a document and insert it
64-
BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database")
65-
.append("count", 1)
66-
.append("info", new BasicDBObject("x", 203).append("y", 102));
70+
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
71+
.append("type", "database")
72+
.append("count", 1)
73+
.append("info", new BasicDBObject("x", 203).append("y", 102));
6774

68-
testCollection.insert(doc);
75+
coll.insert(doc);
6976

7077
// get it (since it's the only one in there since we dropped the rest earlier on)
71-
DBObject myDoc = testCollection.findOne();
78+
DBObject myDoc = coll.findOne();
7279
System.out.println(myDoc);
7380

7481
// now, lets add lots of little documents to the collection so we can explore queries and cursors
7582
for (int i = 0; i < 100; i++) {
76-
testCollection.insert(new BasicDBObject().append("i", i));
83+
coll.insert(new BasicDBObject().append("i", i));
7784
}
78-
System.out.println("total # of documents after inserting 100 small ones (should be 101) " + testCollection.getCount());
85+
System.out.println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount());
7986

8087
// lets get all the documents in the collection and print them out
81-
DBCursor cursor = testCollection.find();
88+
DBCursor cursor = coll.find();
8289
try {
8390
while (cursor.hasNext()) {
8491
System.out.println(cursor.next());
@@ -89,7 +96,7 @@ public static void main(final String[] args) throws UnknownHostException {
8996

9097
// now use a query to get 1 document out
9198
BasicDBObject query = new BasicDBObject("i", 71);
92-
cursor = testCollection.find(query);
99+
cursor = coll.find(query);
93100

94101
try {
95102
while (cursor.hasNext()) {
@@ -99,9 +106,24 @@ public static void main(final String[] args) throws UnknownHostException {
99106
cursor.close();
100107
}
101108

109+
// $ Operators are represented as strings
110+
query = new BasicDBObject("j", new BasicDBObject("$ne", 3))
111+
.append("k", new BasicDBObject("$gt", 10));
112+
113+
cursor = coll.find(query);
114+
115+
try {
116+
while(cursor.hasNext()) {
117+
System.out.println(cursor.next());
118+
}
119+
} finally {
120+
cursor.close();
121+
}
122+
102123
// now use a range query to get a larger subset
103-
query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
104-
cursor = testCollection.find(query);
124+
// find all where i > 50
125+
query = new BasicDBObject("i", new BasicDBObject("$gt", 50));
126+
cursor = coll.find(query);
105127

106128
try {
107129
while (cursor.hasNext()) {
@@ -112,8 +134,8 @@ public static void main(final String[] args) throws UnknownHostException {
112134
}
113135

114136
// range query with multiple constraints
115-
query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30
116-
cursor = testCollection.find(query);
137+
query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30));
138+
cursor = coll.find(query);
117139

118140
try {
119141
while (cursor.hasNext()) {
@@ -123,30 +145,46 @@ public static void main(final String[] args) throws UnknownHostException {
123145
cursor.close();
124146
}
125147

126-
// create an index on the "i" field
127-
testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending
128-
129-
// list the indexes on the collection
130-
List<DBObject> list = testCollection.getIndexInfo();
131-
for (final DBObject o : list) {
132-
System.out.println(o);
148+
// Count all documents in a collection but take a maximum second to do so
149+
coll.find().maxTime(1, SECONDS).count();
150+
151+
// Bulk operations
152+
BulkWriteOperation builder = coll.initializeOrderedBulkOperation();
153+
builder.insert(new BasicDBObject("_id", 1));
154+
builder.insert(new BasicDBObject("_id", 2));
155+
builder.insert(new BasicDBObject("_id", 3));
156+
157+
builder.find(new BasicDBObject("_id", 1)).updateOne(new BasicDBObject("$set", new BasicDBObject("x", 2)));
158+
builder.find(new BasicDBObject("_id", 2)).removeOne();
159+
builder.find(new BasicDBObject("_id", 3)).replaceOne(new BasicDBObject("_id", 3).append("x", 4));
160+
161+
BulkWriteResult result = builder.execute();
162+
System.out.println("Ordered bulk write result : " + result);
163+
164+
// Unordered bulk operation - no guarantee of order of operation
165+
builder = coll.initializeUnorderedBulkOperation();
166+
builder.find(new BasicDBObject("_id", 1)).removeOne();
167+
builder.find(new BasicDBObject("_id", 2)).removeOne();
168+
169+
result = builder.execute();
170+
System.out.println("Ordered bulk write result : " + result);
171+
172+
// parallelScan
173+
ParallelScanOptions parallelScanOptions = ParallelScanOptions
174+
.builder()
175+
.numCursors(3)
176+
.batchSize(300)
177+
.build();
178+
179+
List<Cursor> cursors = coll.parallelScan(parallelScanOptions);
180+
for (Cursor pCursor: cursors) {
181+
while (pCursor.hasNext()) {
182+
System.out.println(pCursor.next());
183+
}
133184
}
134185

135-
// See if the last operation had an error
136-
System.out.println("Last error : " + db.getLastError());
137-
138-
// see if any previous operation had an error
139-
System.out.println("Previous error : " + db.getPreviousError());
140-
141-
// force an error
142-
db.forceError();
143-
144-
// See if the last operation had an error
145-
System.out.println("Last error : " + db.getLastError());
146-
147-
db.resetError();
148-
149186
// release resources
187+
db.dropDatabase();
150188
mongoClient.close();
151189
}
152190
// CHECKSTYLE:ON

0 commit comments

Comments
 (0)