Skip to content

Commit a89a07d

Browse files
author
Michael Pratt
committed
[BAEL-2732] Adding in BSON examples from article
1 parent 970a94b commit a89a07d

File tree

2 files changed

+81
-2
lines changed

2 files changed

+81
-2
lines changed

persistence-modules/java-mongodb/pom.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@
3535
<properties>
3636
<maven.compiler.source>1.8</maven.compiler.source>
3737
<maven.compiler.target>1.8</maven.compiler.target>
38-
<mongo.version>3.4.1</mongo.version>
38+
<mongo.version>3.10.1</mongo.version>
3939
<flapdoodle.version>1.11</flapdoodle.version>
4040
</properties>
4141

42-
</project>
42+
</project>
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.baeldung;
2+
3+
import com.mongodb.client.MongoClient;
4+
import com.mongodb.client.MongoClients;
5+
import com.mongodb.client.MongoCollection;
6+
import com.mongodb.client.MongoDatabase;
7+
import org.bson.Document;
8+
9+
import java.util.ArrayList;
10+
import java.util.Arrays;
11+
import java.util.List;
12+
13+
public class MongoBsonExample
14+
{
15+
public static void main(String[] args)
16+
{
17+
//
18+
// 4.1 Connect to cluster (default is localhost:27017)
19+
//
20+
21+
MongoClient mongoClient = MongoClients.create();
22+
MongoDatabase database = mongoClient.getDatabase("myDB");
23+
MongoCollection<Document> collection = database.getCollection("employees");
24+
25+
//
26+
// 4.2 Insert new document
27+
//
28+
29+
Document employee = new Document()
30+
.append("first_name", "Joe")
31+
.append("last_name", "Smith")
32+
.append("title", "Java Developer")
33+
.append("years_of_service", 3)
34+
.append("skills", Arrays.asList("java", "spring", "mongodb"))
35+
.append("manager", new Document()
36+
.append("first_name", "Sally")
37+
.append("last_name", "Johanson"));
38+
collection.insertOne(employee);
39+
40+
//
41+
// 4.3 Find documents
42+
//
43+
44+
45+
Document query = new Document("last_name", "Smith");
46+
List results = new ArrayList<>();
47+
collection.find(query).into(results);
48+
49+
query =
50+
new Document("$or", Arrays.asList(
51+
new Document("last_name", "Smith"),
52+
new Document("first_name", "Joe")));
53+
results = new ArrayList<>();
54+
collection.find(query).into(results);
55+
56+
//
57+
// 4.4 Update document
58+
//
59+
60+
query = new Document(
61+
"skills",
62+
new Document(
63+
"$elemMatch",
64+
new Document("$eq", "spring")));
65+
Document update = new Document(
66+
"$push",
67+
new Document("skills", "security"));
68+
collection.updateMany(query, update);
69+
70+
//
71+
// 4.5 Delete documents
72+
//
73+
74+
query = new Document(
75+
"years_of_service",
76+
new Document("$lt", 0));
77+
collection.deleteMany(query);
78+
}
79+
}

0 commit comments

Comments
 (0)