|
| 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