|
| 1 | +package com.oracle; |
| 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 com.mongodb.client.model.Filters; |
| 8 | +import com.mongodb.client.model.ReplaceOptions; |
| 9 | +import com.mongodb.client.model.UpdateOptions; |
| 10 | +import com.mongodb.client.model.Updates; |
| 11 | +import org.bson.Document; |
| 12 | +import org.bson.conversions.Bson; |
| 13 | + |
| 14 | +//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or |
| 15 | +// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. |
| 16 | +public class Main { |
| 17 | + public static void main(String[] args) { |
| 18 | + MongoClient client; |
| 19 | + MongoDatabase db; |
| 20 | + String connectString = System.getenv("DB_URI"); |
| 21 | + String dbName = System.getenv("DB_NAME"); |
| 22 | + |
| 23 | + try { |
| 24 | + client = MongoClients.create(connectString); |
| 25 | + db = client.getDatabase(dbName); |
| 26 | + |
| 27 | + System.out.println("Connected!"); |
| 28 | + |
| 29 | + MongoCollection<Document> colors = db.getCollection("colors"); |
| 30 | + colors.deleteMany(new Document()); |
| 31 | + System.out.println("All documents form colors collection deleted."); |
| 32 | + |
| 33 | + colors = db.getCollection("colors"); |
| 34 | + Document d = new Document("name","black"); |
| 35 | + d.append("_id","0001"); |
| 36 | + colors.insertOne(d); |
| 37 | + d = new Document("name","yellow"); |
| 38 | + colors.insertOne(d); |
| 39 | + d = new Document("name","green"); |
| 40 | + colors.insertOne(d); |
| 41 | + System.out.println("Inserts done."); |
| 42 | + |
| 43 | + Bson filter = Filters.eq("_id", "0001"); |
| 44 | + Bson update = Updates.set("name","orange"); |
| 45 | + UpdateOptions options = new UpdateOptions().upsert(true); |
| 46 | + System.out.println(colors.updateOne(filter,update,options)); |
| 47 | + System.out.println("UPDATE with UPSERT done."); |
| 48 | + |
| 49 | + ReplaceOptions replace = new ReplaceOptions().upsert(true); |
| 50 | + d = new Document("_id", "0001"); |
| 51 | + d.append("name","white"); |
| 52 | + colors.replaceOne(filter,d,replace); |
| 53 | + System.out.println("Replace done."); |
| 54 | + |
| 55 | + System.out.println("Printing all documents from colors collection"); |
| 56 | + Bson f = Filters.empty(); |
| 57 | + colors.find(f).forEach(doc -> System.out.println(doc.toJson())); |
| 58 | + |
| 59 | + } |
| 60 | + catch (Exception e) {e.printStackTrace();} |
| 61 | + } |
| 62 | +} |
0 commit comments