├── .gitignore ├── pom.xml ├── README.md └── src └── main └── java └── mongodb └── Main.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | atlas-example.iml 3 | target/ 4 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.mongodb 7 | atlas-example 8 | jar 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 1.8 13 | 1.8 14 | 15 | 16 | 17 | 18 | 19 | org.mongodb 20 | mongodb-driver-sync 21 | 4.0.1 22 | 23 | 24 | 25 | 26 | org.slf4j 27 | slf4j-jdk14 28 | 1.7.28 29 | 30 | 31 | 32 | 33 | 34 | 35 | org.apache.maven.plugins 36 | maven-shade-plugin 37 | 2.1 38 | 39 | 40 | package 41 | 42 | shade 43 | 44 | 45 | 46 | 48 | mongodb.Main 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MongoDB Atlas Java Sample Project 2 | 3 | This repository contains an example application that connects 4 | to a MongoDB instance using the Java MongoDB Driver. You can 5 | use this example application as a starting point for a Java 6 | application that connects to MongoDB Atlas. 7 | 8 | ## Prerequisites 9 | 10 | 1) To build and run this project, you will need IntelliJ IDEA Community 11 | Edition for MacOS, Windows, or Linux. You can download it 12 | [here](https://www.jetbrains.com/idea/). 13 | 14 | 2) A working installation of the [Java 8 JDK](https://developers.redhat.com/products/openjdk/download). 15 | 16 | 3) A working installation of the [Maven](https://maven.apache.org/) build system. (Your IntelliJ installation should include this) 17 | 18 | It is also helpful, but not necessary, to have a working installation of 19 | [Git](https://git-scm.com/downloads) version control. 20 | 21 | Some of these tools may come pre-installed in your programming environment. 22 | 23 | ## Getting Started 24 | 25 | The following instructions explain how to get this project 26 | connected to your instance of MongoDB Atlas. 27 | 28 | ### 1. Download the Repository 29 | 30 | To get started with this sample project, download this repository to your 31 | programming environment. You can either download this project using Git 32 | version control: 33 | 34 | ```bash 35 | git clone git@github.com:mongodb-university/atlas_starter_java.git 36 | ``` 37 | 38 | Or you can download a ZIP archive using your browser 39 | [from GitHub](https://github.com/mongodb-university/atlas_starter_dotnet/archive/master.zip). 40 | If you download this project as a ZIP archive, 41 | [unzip the archive](https://www.wikihow.com/Unzip-a-File) before proceeding. 42 | 43 | ### 2. Open the Project 44 | 45 | 1. In IntelliJ, select `File > Open... ` 46 | 47 | 2. Navigate to the directory containing this project. 48 | 49 | 3. Select the directory `atlas_starter_java`. 50 | 51 | 4. Click `OK`. 52 | 53 | ### 3. Configure Maven 54 | 55 | 1. In IntelliJ, click to expand the `atlas_starter_java` directory. 56 | 57 | 2. Right click on the directory named `src`. 58 | 59 | 3. Select `Mark Directory as` from the context menu. 60 | 61 | 4. Select `Sources Root`. 62 | 63 | ### 4. Configure your Atlas Credentials 64 | 65 | 1. Expand `atlas_starter_java > src > main > java > mongodb > Main`. 66 | 67 | 2. Double-click `Main`. 68 | 69 | 3. On the following lines in `Main`, replace the Atlas connection URI with your own from the Atlas UI. 70 | 71 | ```java 72 | // TODO: 73 | // Replace the placeholder connection string below with your 74 | // Altas cluster specifics. Be sure it includes 75 | // a valid username and password! Note that in a production environment, 76 | // you do not want to store your password in plain-text here. 77 | String mongoUri = ""; 78 | ``` 79 | 80 | 4. Replace the `` section of the Atlas connection URI you just pasted into `Main` with your password! 81 | 82 | ### 5. Run the Project 83 | 84 | 1. Right click `Main`. 85 | 86 | 2. Select `Run 'Main.main()'` from the context menu. 87 | 88 | Congratulations! You have just connected to MongoDB Atlas using the Java MongoDB Driver! 89 | Try modifying the code to experiment with the Driver and MongoDB! 90 | 91 | ## Troubleshooting 92 | 93 | Are you having trouble getting connected to your MongoDB Atlas instance? Double-check the following: 94 | 95 | 1. Have you replaced the `mongoUri` variable with a valid connection string provided by the Atlas UI? 96 | 97 | 2. Have you [whitelisted your current IP address](https://docs.atlas.mongodb.com/security-whitelist/) in the Atlas UI? 98 | 99 | 3. Do you have a [working installation of Java](https://stackoverflow.com/questions/18888220/how-to-check-whether-java-is-installed-on-the-computer)? 100 | -------------------------------------------------------------------------------- /src/main/java/mongodb/Main.java: -------------------------------------------------------------------------------- 1 | package mongodb; 2 | 3 | import com.mongodb.ConnectionString; 4 | import com.mongodb.MongoClientSettings; 5 | import com.mongodb.MongoException; 6 | import com.mongodb.client.MongoClient; 7 | import com.mongodb.client.MongoClients; 8 | import com.mongodb.client.MongoCollection; 9 | import com.mongodb.client.MongoCursor; 10 | import com.mongodb.client.MongoDatabase; 11 | import com.mongodb.client.model.Filters; 12 | import com.mongodb.client.model.FindOneAndUpdateOptions; 13 | import com.mongodb.client.model.ReturnDocument; 14 | import com.mongodb.client.model.Updates; 15 | import com.mongodb.client.result.DeleteResult; 16 | import com.mongodb.client.result.InsertManyResult; 17 | import org.bson.codecs.configuration.CodecRegistry; 18 | import org.bson.codecs.pojo.PojoCodecProvider; 19 | import org.bson.conversions.Bson; 20 | 21 | import java.util.ArrayList; 22 | import java.util.Arrays; 23 | import java.util.List; 24 | import java.util.logging.Level; 25 | import java.util.logging.Logger; 26 | 27 | import static org.bson.codecs.configuration.CodecRegistries.fromProviders; 28 | import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; 29 | 30 | public class Main { 31 | // a few pre-wired recipes we can insert into the database as examples. 32 | public static List recipes = Arrays.asList( 33 | new Recipe("elotes", 34 | Arrays.asList("corn", "mayonnaise", "cotija cheese", "sour cream", "lime" ), 35 | 35), 36 | new Recipe("loco moco", 37 | Arrays.asList("ground beef", "butter", "onion", "egg", "bread bun", "mushrooms" ), 38 | 54), 39 | new Recipe("patatas bravas", 40 | Arrays.asList("potato", "tomato", "olive oil", "onion", "garlic", "paprika" ), 41 | 80), 42 | new Recipe("fried rice", 43 | Arrays.asList("rice", "soy sauce", "egg", "onion", "pea", "carrot", "sesame oil" ), 44 | 40) 45 | ); 46 | 47 | public static void main(String[] args) { 48 | Logger.getLogger( "org.mongodb.driver" ).setLevel(Level.WARNING); 49 | // TODO: 50 | // Replace the placeholder connection string below with your 51 | // Altas cluster specifics. Be sure it includes 52 | // a valid username and password! Note that in a production environment, 53 | // you do not want to store your password in plain-text here. 54 | ConnectionString mongoUri = new ConnectionString(""); 55 | 56 | // Provide the name of the database and collection you want to use. 57 | // If they don't already exist, the driver and Atlas will create them 58 | // automatically when you first write data. 59 | String dbName = "myDatabase"; 60 | String collectionName = "recipes"; 61 | 62 | // a CodecRegistry tells the Driver how to move data between Java POJOs (Plain Old Java Objects) and MongoDB documents 63 | CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), 64 | fromProviders(PojoCodecProvider.builder().automatic(true).build())); 65 | 66 | // The MongoClient defines the connection to our MongoDB datastore instance (Atlas) using MongoClientSettings 67 | // You can create a MongoClientSettings with a Builder to configure codecRegistries, connection strings, and more 68 | MongoClientSettings settings = MongoClientSettings.builder() 69 | .codecRegistry(pojoCodecRegistry) 70 | .applyConnectionString(mongoUri).build(); 71 | 72 | MongoClient mongoClient = null; 73 | try { 74 | mongoClient = MongoClients.create(settings); 75 | } catch (MongoException me) { 76 | System.err.println("Unable to connect to the MongoDB instance due to an error: " + me); 77 | System.exit(1); 78 | } 79 | 80 | // MongoDatabase defines a connection to a specific MongoDB database 81 | MongoDatabase database = mongoClient.getDatabase(dbName); 82 | // MongoCollection defines a connection to a specific collection of documents in a specific database 83 | MongoCollection collection = database.getCollection(collectionName, Recipe.class); 84 | 85 | /* *** INSERT DOCUMENTS *** 86 | * 87 | * You can insert individual documents using collection.insert(). 88 | * In this example, we're going to create 4 documents and then 89 | * insert them all in one call with insertMany(). 90 | */ 91 | 92 | try { 93 | // recipes is a static variable defined above 94 | InsertManyResult result = collection.insertMany(recipes); 95 | System.out.println("Inserted " + result.getInsertedIds().size() + " documents.\n"); 96 | } catch (MongoException me) { 97 | System.err.println("Unable to insert any recipes into MongoDB due to an error: " + me); 98 | System.exit(1); 99 | } 100 | 101 | /* *** FIND DOCUMENTS *** 102 | * 103 | * Now that we have data in Atlas, we can read it. To retrieve all of 104 | * the data in a collection, we call find() with an empty filter. We can 105 | * retrieve an iterator to return the results from our call to the find() 106 | * method. Here we use the try-with-resources pattern to automatically 107 | * close the cursor once we finish reading the recipes. 108 | */ 109 | 110 | try (MongoCursor cursor = collection.find().iterator()) { 111 | while (cursor.hasNext()) { 112 | Recipe currentRecipe = cursor.next(); 113 | System.out.printf("%s has %d ingredients and takes %d minutes to make\n", currentRecipe.getName(), currentRecipe.getIngredients().size(), currentRecipe.getPrepTimeInMinutes()); 114 | } 115 | } catch (MongoException me) { 116 | System.err.println("Unable to find any recipes in MongoDB due to an error: " + me); 117 | } 118 | 119 | // We can also find a single document. Let's find the first document 120 | // that has the string "potato" in the ingredients list. We 121 | // use the Filters.eq() method to search for any values in any 122 | // ingredients list that match the string "potato": 123 | 124 | Bson findPotato = Filters.eq("ingredients", "potato"); 125 | try { 126 | Recipe firstPotato = collection.find(findPotato).first(); 127 | if (firstPotato == null) { 128 | System.out.println("Couldn't find any recipes containing 'potato' as an ingredient in MongoDB."); 129 | System.exit(1); 130 | } 131 | } catch (MongoException me) { 132 | System.err.println("Unable to find a recipe to update in MongoDB due to an error: " + me); 133 | System.exit(1); 134 | } 135 | 136 | /* *** UPDATE A DOCUMENT *** 137 | * 138 | * You can update a single document or multiple documents in a single call. 139 | * 140 | * Here we update the PrepTimeInMinutes value on the document we 141 | * just found. 142 | */ 143 | Bson updateFilter = Updates.set("prepTimeInMinutes", 72); 144 | 145 | // The following FindOneAndUpdateOptions specify that we want it to return 146 | // the *updated* document to us. By default, we get the document as it was *before* 147 | // the update. 148 | FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER); 149 | 150 | // The updatedDocument object is a Recipe object that reflects the 151 | // changes we just made. 152 | try { 153 | Recipe updatedDocument = collection.findOneAndUpdate(findPotato, 154 | updateFilter, options); 155 | if (updatedDocument == null) { 156 | System.out.println("Couldn't update the recipe. Did someone (or something) delete it?"); 157 | } else { 158 | System.out.println("\nUpdated the recipe to: " + updatedDocument); 159 | } 160 | } catch (MongoException me) { 161 | System.err.println("Unable to update any recipes due to an error: " + me); 162 | } 163 | 164 | /* *** DELETE DOCUMENTS *** 165 | * 166 | * As with other CRUD methods, you can delete a single document 167 | * or all documents that match a specified filter. To delete all 168 | * of the documents in a collection, pass an empty filter to 169 | * the deleteMany() method. In this example, we'll delete 2 of 170 | * the recipes. 171 | */ 172 | Bson deleteFilter = Filters.in("name", Arrays.asList("elotes", "fried rice")); 173 | try { 174 | DeleteResult deleteResult = collection 175 | .deleteMany(deleteFilter); 176 | System.out.printf("\nDeleted %d documents.\n", deleteResult.getDeletedCount()); 177 | } catch (MongoException me) { 178 | System.err.println("Unable to delete any recipes due to an error: " + me); 179 | } 180 | 181 | // always close the connection when done working with the client 182 | mongoClient.close(); 183 | } 184 | 185 | // POJO (Plain Old Java Object) class defining a recipe. This class is a POJO because it contains getters and 186 | // setters for every member variable as well as an empty constructor. 187 | public static class Recipe { 188 | private String name; 189 | private List ingredients; 190 | private int prepTimeInMinutes; 191 | 192 | public Recipe(String name, List ingredients, int prepTimeInMinutes) { 193 | this.name = name; 194 | this.ingredients = ingredients; 195 | this.prepTimeInMinutes = prepTimeInMinutes; 196 | } 197 | 198 | // empty constructor required when we fetch data from the database -- getters and setters are later used to 199 | // set values for member variables 200 | public Recipe() { 201 | ingredients = new ArrayList(); 202 | name = ""; 203 | } 204 | 205 | @Override 206 | public String toString() { 207 | final StringBuffer sb = new StringBuffer("Recipe{"); 208 | sb.append("name=").append(name); 209 | sb.append(", ingredients=").append(ingredients); 210 | sb.append(", prepTimeInMinutes=").append(prepTimeInMinutes); 211 | sb.append('}'); 212 | return sb.toString(); 213 | } 214 | 215 | public String getName() { 216 | return name; 217 | } 218 | 219 | public void setName(String name) { 220 | this.name = name; 221 | } 222 | 223 | public List getIngredients() { 224 | return ingredients; 225 | } 226 | 227 | public void setIngredients(List ingredients) { 228 | this.ingredients = ingredients; 229 | } 230 | 231 | public int getPrepTimeInMinutes() { 232 | return prepTimeInMinutes; 233 | } 234 | 235 | public void setPrepTimeInMinutes(int prepTimeInMinutes) { 236 | this.prepTimeInMinutes = prepTimeInMinutes; 237 | } 238 | } 239 | } 240 | --------------------------------------------------------------------------------