├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── test └── java └── com └── mechanitis └── mongodb └── gettingstarted ├── Exercise10UpdateByReplacementTest.java ├── Exercise11UpdateAFieldTest.java ├── Exercise12UpdateMultipleDocumentsTest.java ├── Exercise13UpsertTest.java ├── Exercise14RemoveTest.java ├── Exercise1ConnectingTest.java ├── Exercise2MongoClientTest.java ├── Exercise3InsertTest.java ├── Exercise4RetrieveTest.java ├── Exercise5SimpleQueryTest.java ├── Exercise6SelectFieldsTest.java ├── Exercise7QueryOperatorsTest.java ├── Exercise8SkipAndLimitTest.java ├── Exercise9IndexTest.java └── person ├── Address.java ├── Person.java └── PersonAdaptor.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | out 4 | build 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Getting started with MongoDB and Java 2 | ======================= 3 | 4 | 5 | Step by step examples (via unit tests) of how to do simple operations with the 2.12 version of the MongoDB Java driver. Use this code to play along with the Getting Started guides: 6 | 7 | [Getting Started with MongoDB and Java: Part I](http://blog.mongodb.org/post/94065240033/getting-started-with-mongodb-and-java-part-i) 8 | [Getting Started with MongoDB and Java: Part II](http://blog.mongodb.org/post/94724924068/getting-started-with-mongodb-and-java-part-ii) 9 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | sourceCompatibility = 1.7 4 | version = '1.0' 5 | 6 | repositories { 7 | mavenCentral() 8 | } 9 | 10 | dependencies { 11 | testCompile 'org.mongodb:mongo-java-driver:2.12.1' 12 | testCompile 'org.hamcrest:hamcrest-all:1.3' 13 | testCompile 'junit:junit:4.11' 14 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trishagee/mongodb-getting-started/4ac49327a26fed8b6e60c2222aed40df43672b89/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri May 02 12:44:15 CEST 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=http\://services.gradle.org/distributions/gradle-1.9-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'getting-started' 2 | 3 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise10UpdateByReplacementTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBObject; 9 | import com.mongodb.MongoClient; 10 | import com.mongodb.MongoClientURI; 11 | import com.mongodb.WriteResult; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | import java.util.Collections; 18 | import java.util.List; 19 | 20 | import static java.util.Arrays.asList; 21 | import static org.hamcrest.CoreMatchers.is; 22 | import static org.junit.Assert.assertThat; 23 | 24 | public class Exercise10UpdateByReplacementTest { 25 | private DB database; 26 | private DBCollection collection; 27 | 28 | @Test 29 | public void shouldReplaceWholeDBObjectWithNewOne() { 30 | // Given 31 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 32 | collection.insert(PersonAdaptor.toDBObject(bob)); 33 | 34 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 35 | collection.insert(PersonAdaptor.toDBObject(charlie)); 36 | 37 | // When 38 | Person updatedCharlieObject = new Person("charlie", "Charles the Suave", new Address("A new street", "GreatCity", 7654321), 39 | Collections.emptyList()); 40 | // TODO create query to find Charlie by ID 41 | DBObject findCharlie = null; 42 | // TODO do an update replacing the whole previous Document with the new one 43 | WriteResult resultOfUpdate = null; 44 | 45 | // Then 46 | assertThat(resultOfUpdate.getN(), is(1)); 47 | 48 | DBObject newCharlieDBObject = collection.find(findCharlie).toArray().get(0); 49 | // all values should have been updated to the new object values 50 | assertThat((String) newCharlieDBObject.get("_id"), is(updatedCharlieObject.getId())); 51 | assertThat((String) newCharlieDBObject.get("name"), is(updatedCharlieObject.getName())); 52 | assertThat((List) newCharlieDBObject.get("books"), is(updatedCharlieObject.getBookIds())); 53 | DBObject address = (DBObject) newCharlieDBObject.get("address"); 54 | assertThat((String) address.get("street"), is(updatedCharlieObject.getAddress().getStreet())); 55 | assertThat((String) address.get("city"), is(updatedCharlieObject.getAddress().getTown())); 56 | assertThat((int) address.get("phone"), is(updatedCharlieObject.getAddress().getPhone())); 57 | } 58 | 59 | @Before 60 | public void setUp() throws UnknownHostException { 61 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 62 | database = mongoClient.getDB("Examples"); 63 | collection = database.getCollection("people"); 64 | } 65 | 66 | @After 67 | public void tearDown() { 68 | database.dropDatabase(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise11UpdateAFieldTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBObject; 9 | import com.mongodb.MongoClient; 10 | import com.mongodb.MongoClientURI; 11 | import com.mongodb.WriteResult; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | import java.util.List; 18 | 19 | import static java.util.Arrays.asList; 20 | import static org.hamcrest.CoreMatchers.is; 21 | import static org.junit.Assert.assertThat; 22 | 23 | public class Exercise11UpdateAFieldTest { 24 | private DB database; 25 | private DBCollection collection; 26 | 27 | @Test 28 | public void shouldUpdateCharliesAddress() { 29 | // Given 30 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 31 | collection.insert(PersonAdaptor.toDBObject(bob)); 32 | 33 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 34 | collection.insert(PersonAdaptor.toDBObject(charlie)); 35 | 36 | String charliesNewAddress = "987 The New Street"; 37 | 38 | // When 39 | // TODO create query to find Charlie by ID 40 | DBObject findCharlie = null; 41 | // TODO use the query to find charlie and update his street with the new address 42 | WriteResult resultOfUpdate = null; 43 | 44 | // Then 45 | assertThat(resultOfUpdate.getN(), is(1)); 46 | 47 | DBObject newCharlie = collection.find(findCharlie).toArray().get(0); 48 | // this stuff should all be the same 49 | assertThat((String) newCharlie.get("_id"), is(charlie.getId())); 50 | assertThat((String) newCharlie.get("name"), is(charlie.getName())); 51 | 52 | // the address street, and only the street, should have changed 53 | DBObject address = (DBObject) newCharlie.get("address"); 54 | assertThat((String) address.get("street"), is(charliesNewAddress)); 55 | assertThat((String) address.get("city"), is(charlie.getAddress().getTown())); 56 | assertThat((int) address.get("phone"), is(charlie.getAddress().getPhone())); 57 | } 58 | 59 | @Test 60 | public void shouldAddANewFieldToAnExistingDocument() { 61 | // Given 62 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 63 | collection.insert(PersonAdaptor.toDBObject(bob)); 64 | 65 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 66 | collection.insert(PersonAdaptor.toDBObject(charlie)); 67 | 68 | // When 69 | // TODO create query to find Charlie by ID 70 | DBObject findCharlie = null; 71 | // TODO use the query to find charlie and update his street with the new address 72 | WriteResult resultOfUpdate = null; 73 | 74 | // Then 75 | assertThat(resultOfUpdate.getN(), is(1)); 76 | 77 | DBObject newCharlie = collection.find(findCharlie).toArray().get(0); 78 | // this stuff should all be the same 79 | assertThat((String) newCharlie.get("_id"), is(charlie.getId())); 80 | assertThat((String) newCharlie.get("name"), is(charlie.getName())); 81 | assertThat((String) newCharlie.get("newField"), is("A New Value")); 82 | } 83 | 84 | //BONUS 85 | @Test 86 | public void shouldAddAnotherBookToBobsBookIds() { 87 | // Given 88 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 89 | collection.insert(PersonAdaptor.toDBObject(bob)); 90 | 91 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 92 | collection.insert(PersonAdaptor.toDBObject(charlie)); 93 | 94 | // When 95 | // TODO create query to find Bob by ID 96 | DBObject findBob = null; 97 | // TODO update the only Bob document to add the ID '66' to the array of Book IDs 98 | 99 | // Then 100 | DBObject newBob = collection.find(findBob).toArray().get(0); 101 | 102 | assertThat((String) newBob.get("name"), is(bob.getName())); 103 | 104 | // there should be another item in the array 105 | List bobsBooks = (List) newBob.get("books"); 106 | // note these are ordered 107 | assertThat(bobsBooks.size(), is(3)); 108 | assertThat(bobsBooks.get(0), is(27464)); 109 | assertThat(bobsBooks.get(1), is(747854)); 110 | assertThat(bobsBooks.get(2), is(66)); 111 | } 112 | 113 | @Before 114 | public void setUp() throws UnknownHostException { 115 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 116 | database = mongoClient.getDB("Examples"); 117 | collection = database.getCollection("people"); 118 | } 119 | 120 | @After 121 | public void tearDown() { 122 | database.dropDatabase(); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise12UpdateMultipleDocumentsTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.BasicDBObject; 7 | import com.mongodb.DB; 8 | import com.mongodb.DBCollection; 9 | import com.mongodb.DBObject; 10 | import com.mongodb.MongoClient; 11 | import com.mongodb.MongoClientURI; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | import java.util.Collections; 18 | import java.util.List; 19 | 20 | import static java.util.Arrays.asList; 21 | import static org.hamcrest.CoreMatchers.is; 22 | import static org.hamcrest.CoreMatchers.nullValue; 23 | import static org.junit.Assert.assertThat; 24 | 25 | public class Exercise12UpdateMultipleDocumentsTest { 26 | private DB database; 27 | private DBCollection collection; 28 | 29 | //Multi=false 30 | @Test 31 | public void shouldOnlyUpdateTheFirstDBObjectMatchingTheQuery() { 32 | // Given 33 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 34 | collection.insert(PersonAdaptor.toDBObject(bob)); 35 | 36 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 37 | collection.insert(PersonAdaptor.toDBObject(charlie)); 38 | 39 | Person emily = new Person("emily", "Emily", new Address("5", "Some Town", 646383), Collections.emptyList()); 40 | collection.insert(PersonAdaptor.toDBObject(emily)); 41 | 42 | // When 43 | // TODO create query to find everyone with 'LondonTown' as their city 44 | DBObject findLondoners = null; 45 | assertThat(collection.find(findLondoners).count(), is(2)); 46 | 47 | // TODO update only the first Londonder here to have a new field, "wasUpdated", with a value of true 48 | 49 | 50 | // Then 51 | List londoners = collection.find(findLondoners).sort(new BasicDBObject("_id", 1)).toArray(); 52 | assertThat(londoners.size(), is(2)); 53 | 54 | assertThat((String) londoners.get(0).get("name"), is(bob.getName())); 55 | assertThat((boolean) londoners.get(0).get("wasUpdated"), is(true)); 56 | 57 | assertThat((String) londoners.get(1).get("name"), is(charlie.getName())); 58 | assertThat(londoners.get(1).get("wasUpdated"), is(nullValue())); 59 | } 60 | 61 | //Multi=true 62 | @Test 63 | public void shouldUpdateEveryoneLivingInLondon() { 64 | // Given 65 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 66 | collection.insert(PersonAdaptor.toDBObject(bob)); 67 | 68 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 69 | collection.insert(PersonAdaptor.toDBObject(charlie)); 70 | 71 | Person emily = new Person("emily", "Emily", new Address("5", "Some Town", 646383), Collections.emptyList()); 72 | collection.insert(PersonAdaptor.toDBObject(emily)); 73 | 74 | // When 75 | // TODO create query to find everyone with 'LondonTown' as their city 76 | DBObject findLondoners = null; 77 | assertThat(collection.find(findLondoners).count(), is(2)); 78 | 79 | // TODO update all Londonders here to have a new field, "wasUpdated", with a value of true 80 | 81 | 82 | // Then 83 | List londoners = collection.find(findLondoners).sort(new BasicDBObject("_id", 1)).toArray(); 84 | assertThat(londoners.size(), is(2)); 85 | 86 | DBObject firstLondoner = londoners.get(0); 87 | assertThat((String) firstLondoner.get("name"), is(bob.getName())); 88 | assertThat((boolean) firstLondoner.get("wasUpdated"), is(true)); 89 | 90 | DBObject secondLondoner = londoners.get(1); 91 | assertThat((String) secondLondoner.get("name"), is(charlie.getName())); 92 | assertThat((boolean) secondLondoner.get("wasUpdated"), is(true)); 93 | } 94 | 95 | @Before 96 | public void setUp() throws UnknownHostException { 97 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 98 | database = mongoClient.getDB("Examples"); 99 | collection = database.getCollection("people"); 100 | } 101 | 102 | @After 103 | public void tearDown() { 104 | database.dropDatabase(); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise13UpsertTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBObject; 9 | import com.mongodb.MongoClient; 10 | import com.mongodb.MongoClientURI; 11 | import com.mongodb.WriteResult; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | import java.util.Collections; 18 | 19 | import static java.util.Arrays.asList; 20 | import static org.hamcrest.CoreMatchers.is; 21 | import static org.junit.Assert.assertThat; 22 | 23 | public class Exercise13UpsertTest { 24 | private DB database; 25 | private DBCollection collection; 26 | 27 | //Upsert 28 | @Test 29 | public void shouldOnlyInsertDBObjectIfItDidNotExistWhenUpsertIsTrue() { 30 | // Given 31 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 32 | collection.insert(PersonAdaptor.toDBObject(bob)); 33 | 34 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 35 | collection.insert(PersonAdaptor.toDBObject(charlie)); 36 | 37 | // new person not in the database yet 38 | Person claire = new Person("claire", "Claire", new Address("1", "Town", 836558493), Collections.emptyList()); 39 | 40 | // When 41 | // TODO create query to find Claire by ID 42 | DBObject findClaire = null; 43 | // TODO Perform an update with this new person to show it does NOT get added to the database 44 | WriteResult resultOfUpdate = null; 45 | 46 | // Then 47 | assertThat(resultOfUpdate.getN(), is(0)); 48 | // without upsert this should not have been inserted 49 | assertThat(collection.find(findClaire).count(), is(0)); 50 | 51 | 52 | // When 53 | // TODO Perform an update with this new person to show it DOES get added to the database 54 | WriteResult resultOfUpsert = null; 55 | 56 | // Then 57 | assertThat(resultOfUpsert.getN(), is(1)); 58 | 59 | DBObject newClaireDBObject = collection.find(findClaire).toArray().get(0); 60 | // all values should have been updated to the new object values 61 | assertThat((String) newClaireDBObject.get("_id"), is(claire.getId())); 62 | } 63 | 64 | @Before 65 | public void setUp() throws UnknownHostException { 66 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 67 | database = mongoClient.getDB("Examples"); 68 | collection = database.getCollection("people"); 69 | } 70 | 71 | @After 72 | public void tearDown() { 73 | database.dropDatabase(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise14RemoveTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBObject; 9 | import com.mongodb.MongoClient; 10 | import com.mongodb.MongoClientURI; 11 | import com.mongodb.WriteResult; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | import java.util.Collections; 18 | import java.util.List; 19 | 20 | import static java.util.Arrays.asList; 21 | import static org.hamcrest.CoreMatchers.is; 22 | import static org.hamcrest.CoreMatchers.not; 23 | import static org.junit.Assert.assertThat; 24 | 25 | public class Exercise14RemoveTest { 26 | private DB database; 27 | private DBCollection collection; 28 | 29 | @Test 30 | public void shouldDeleteOnlyCharlieFromTheDatabase() { 31 | // Given 32 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 33 | collection.insert(PersonAdaptor.toDBObject(bob)); 34 | 35 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 36 | collection.insert(PersonAdaptor.toDBObject(charlie)); 37 | 38 | Person emily = new Person("emily", "Emily", new Address("5", "Some Town", 646383), Collections.emptyList()); 39 | collection.insert(PersonAdaptor.toDBObject(emily)); 40 | 41 | // When 42 | // TODO create a query to find charlie by ID 43 | DBObject query = null; 44 | // TODO execute the remove 45 | WriteResult resultOfRemove = null; 46 | 47 | // Then 48 | assertThat(resultOfRemove.getN(), is(1)); 49 | 50 | List remainingPeople = collection.find().toArray(); 51 | assertThat(remainingPeople.size(), is(2)); 52 | 53 | for (final DBObject remainingPerson : remainingPeople) { 54 | assertThat((String) remainingPerson.get("_id"), is(not(charlie.getId()))); 55 | } 56 | } 57 | 58 | @Test 59 | public void shouldDeletePeopleWhoLiveInLondon() { 60 | // Given 61 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 62 | collection.insert(PersonAdaptor.toDBObject(bob)); 63 | 64 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 65 | collection.insert(PersonAdaptor.toDBObject(charlie)); 66 | 67 | Person emily = new Person("emily", "Emily", new Address("5", "Some Town", 646383), Collections.emptyList()); 68 | collection.insert(PersonAdaptor.toDBObject(emily)); 69 | 70 | // When 71 | // TODO create the query to check the city field inside the address subdocument for 'LondonTown' 72 | DBObject query = null; 73 | // TODO execute the remove 74 | WriteResult resultOfRemove = null; 75 | 76 | // Then 77 | assertThat(resultOfRemove.getN(), is(2)); 78 | 79 | List remainingPeople = collection.find().toArray(); 80 | assertThat(remainingPeople.size(), is(1)); 81 | 82 | assertThat((String) remainingPeople.get(0).get("_id"), is(emily.getId())); 83 | } 84 | 85 | @Before 86 | public void setUp() throws UnknownHostException { 87 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 88 | database = mongoClient.getDB("Examples"); 89 | collection = database.getCollection("people"); 90 | } 91 | 92 | @After 93 | public void tearDown() { 94 | database.dropDatabase(); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise1ConnectingTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mongodb.MongoClient; 4 | import org.junit.Test; 5 | 6 | import static org.hamcrest.CoreMatchers.is; 7 | import static org.hamcrest.CoreMatchers.notNullValue; 8 | import static org.junit.Assert.assertThat; 9 | 10 | public class Exercise1ConnectingTest { 11 | @Test 12 | public void shouldCreateANewMongoClientConnectedToLocalhost() throws Exception { 13 | // When 14 | // TODO: get/create the MongoClient 15 | MongoClient mongoClient = null; 16 | 17 | // Then 18 | assertThat(mongoClient, is(notNullValue())); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise2MongoClientTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mongodb.BasicDBObject; 4 | import com.mongodb.DB; 5 | import com.mongodb.DBCollection; 6 | import com.mongodb.MongoClient; 7 | import org.junit.Test; 8 | 9 | import java.net.UnknownHostException; 10 | 11 | import static org.hamcrest.CoreMatchers.is; 12 | import static org.hamcrest.CoreMatchers.notNullValue; 13 | import static org.junit.Assert.assertThat; 14 | 15 | public class Exercise2MongoClientTest { 16 | @Test 17 | public void shouldGetADatabaseFromTheMongoClient() throws Exception { 18 | // Given 19 | // TODO any setup 20 | 21 | // When 22 | //TODO get the database from the client 23 | DB database = null; 24 | 25 | // Then 26 | assertThat(database, is(notNullValue())); 27 | } 28 | 29 | @Test 30 | public void shouldGetACollectionFromTheDatabase() throws Exception { 31 | // Given 32 | // TODO any setup 33 | 34 | // When 35 | // TODO get collection 36 | DBCollection collection = null; 37 | 38 | // Then 39 | assertThat(collection, is(notNullValue())); 40 | } 41 | 42 | @Test(expected = Exception.class) 43 | public void shouldNotBeAbleToUseMongoClientAfterItHasBeenClosed() throws UnknownHostException { 44 | // Given 45 | MongoClient mongoClient = new MongoClient(); 46 | 47 | // When 48 | // TODO close the mongoClient 49 | 50 | // Then 51 | mongoClient.getDB("SomeDatabase").getCollection("coll").insert(new BasicDBObject("field", "value")); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise3InsertTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBObject; 9 | import com.mongodb.MongoClient; 10 | import com.mongodb.MongoClientURI; 11 | import org.junit.Test; 12 | 13 | import java.net.UnknownHostException; 14 | 15 | import static java.util.Arrays.asList; 16 | import static org.hamcrest.CoreMatchers.is; 17 | import static org.junit.Assert.assertThat; 18 | 19 | public class Exercise3InsertTest { 20 | @Test 21 | public void shouldTurnAPersonIntoADBObject() { 22 | // Given 23 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 24 | 25 | // When 26 | DBObject bobAsDBObject = PersonAdaptor.toDBObject(bob); 27 | 28 | // Then 29 | String expectedDBObject = "{" + 30 | " \"_id\" : \"bob\" ," + 31 | " \"name\" : \"Bob The Amazing\" ," + 32 | " \"address\" : {" + 33 | " \"street\" : \"123 Fake St\" ," + 34 | " \"city\" : \"LondonTown\" ," + 35 | " \"phone\" : 1234567890" + 36 | "} ," + 37 | " \"books\" : [ 27464 , 747854]" + 38 | "}"; 39 | assertThat(bobAsDBObject.toString(), is(expectedDBObject)); 40 | } 41 | 42 | @Test 43 | public void shouldBeAbleToSaveAPerson() throws UnknownHostException { 44 | // Given 45 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 46 | DB database = mongoClient.getDB("Examples"); 47 | DBCollection collection = database.getCollection("people"); 48 | 49 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 50 | 51 | // When 52 | // TODO: insert Charlie into the collection 53 | 54 | // Then 55 | assertThat(collection.find().count(), is(1)); 56 | 57 | // Clean up 58 | database.dropDatabase(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise4RetrieveTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBCursor; 9 | import com.mongodb.DBObject; 10 | import com.mongodb.MongoClient; 11 | import com.mongodb.MongoClientURI; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | 18 | import static java.util.Arrays.asList; 19 | import static org.hamcrest.CoreMatchers.is; 20 | import static org.junit.Assert.assertThat; 21 | 22 | @SuppressWarnings("unchecked") 23 | public class Exercise4RetrieveTest { 24 | private DB database; 25 | private DBCollection collection; 26 | 27 | @Before 28 | public void setUp() throws UnknownHostException { 29 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 30 | database = mongoClient.getDB("Examples"); 31 | collection = database.getCollection("people"); 32 | } 33 | 34 | @Test 35 | public void shouldRetrieveBobFromTheDatabaseWhenHeIsTheOnlyOneInThere() { 36 | // Given 37 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 38 | collection.insert(PersonAdaptor.toDBObject(bob)); 39 | 40 | // When 41 | // TODO: get this from querying the collection. Hint: you can find just one 42 | DBObject result = null; 43 | 44 | // Then 45 | assertThat((String) result.get("_id"), is("bob")); 46 | } 47 | 48 | @Test 49 | public void shouldRetrieveEverythingFromTheDatabase() { 50 | // Given 51 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 52 | collection.insert(PersonAdaptor.toDBObject(charlie)); 53 | 54 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 55 | collection.insert(PersonAdaptor.toDBObject(bob)); 56 | 57 | // When 58 | // TODO: get a cursor with everything in the database 59 | DBCursor cursor = null; 60 | 61 | // Then 62 | assertThat(cursor.size(), is(2)); 63 | // they should come back in the same order they were put in 64 | assertThat((String) cursor.next().get("_id"), is("charlie")); 65 | assertThat((String) cursor.next().get("_id"), is("bob")); 66 | } 67 | 68 | @Test 69 | public void shouldSearchForAndReturnOnlyBobFromTheDatabaseWhenMorePeopleExist() { 70 | // Given 71 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 72 | collection.insert(PersonAdaptor.toDBObject(charlie)); 73 | 74 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 75 | collection.insert(PersonAdaptor.toDBObject(bob)); 76 | 77 | // When 78 | // TODO create the query document 79 | DBObject query = null; 80 | DBCursor cursor = collection.find(query); 81 | 82 | // Then 83 | assertThat(cursor.count(), is(1)); 84 | assertThat((String) cursor.one().get("name"), is("Bob The Amazing")); 85 | } 86 | 87 | @After 88 | public void tearDown() { 89 | database.dropDatabase(); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise5SimpleQueryTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBCursor; 9 | import com.mongodb.DBObject; 10 | import com.mongodb.MongoClient; 11 | import com.mongodb.MongoClientURI; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | 18 | import static java.util.Arrays.asList; 19 | import static org.hamcrest.CoreMatchers.is; 20 | import static org.junit.Assert.assertThat; 21 | 22 | public class Exercise5SimpleQueryTest { 23 | private DB database; 24 | private DBCollection collection; 25 | 26 | @Test 27 | public void shouldFindAllDBObjectsWithTheNameCharles() { 28 | // Given 29 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 30 | collection.insert(PersonAdaptor.toDBObject(charlie)); 31 | 32 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 33 | collection.insert(PersonAdaptor.toDBObject(bob)); 34 | 35 | // When 36 | // TODO create the correct query to find Charlie by name 37 | DBObject query = null; 38 | // TODO use this query to get a List of matching Documents from the database 39 | DBCursor results = null; 40 | 41 | // Then 42 | assertThat(results.size(), is(1)); 43 | assertThat((String) results.next().get("_id"), is(charlie.getId())); 44 | } 45 | 46 | @Before 47 | public void setUp() throws UnknownHostException { 48 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 49 | database = mongoClient.getDB("Examples"); 50 | collection = database.getCollection("people"); 51 | } 52 | 53 | @After 54 | public void tearDown() { 55 | database.dropDatabase(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise6SelectFieldsTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBCursor; 9 | import com.mongodb.DBObject; 10 | import com.mongodb.MongoClient; 11 | import com.mongodb.MongoClientURI; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | import java.util.List; 18 | 19 | import static java.util.Arrays.asList; 20 | import static org.hamcrest.CoreMatchers.is; 21 | import static org.hamcrest.CoreMatchers.nullValue; 22 | import static org.junit.Assert.assertThat; 23 | 24 | public class Exercise6SelectFieldsTest { 25 | private DB database; 26 | private DBCollection collection; 27 | 28 | @Test 29 | public void shouldFindAllDBObjectsWithTheNameCharlesAndOnlyReturnNameAndId() { 30 | // Given 31 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 32 | collection.insert(PersonAdaptor.toDBObject(charlie)); 33 | 34 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 35 | collection.insert(PersonAdaptor.toDBObject(bob)); 36 | 37 | // When 38 | // TODO create the correct query to find Charlie by name (see above) 39 | DBObject query = null; 40 | // TODO use this query, combined with the "fields" selector, to get a list of result documents with only the name and ID fields 41 | DBCursor results = null; 42 | 43 | // Then 44 | assertThat(results.size(), is(1)); 45 | DBObject theOnlyResult = results.next(); 46 | assertThat((String) theOnlyResult.get("_id"), is(charlie.getId())); 47 | assertThat((String) theOnlyResult.get("name"), is(charlie.getName())); 48 | assertThat(theOnlyResult.get("address"), is(nullValue())); 49 | assertThat(theOnlyResult.get("books"), is(nullValue())); 50 | } 51 | 52 | //BONUS 53 | @Test 54 | public void shouldFindAllDBObjectsWithTheNameCharlesAndExcludeAddressInReturn() { 55 | // Given 56 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 57 | collection.insert(PersonAdaptor.toDBObject(charlie)); 58 | 59 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854)); 60 | collection.insert(PersonAdaptor.toDBObject(bob)); 61 | 62 | // When 63 | // TODO create the correct query to find Charlie by name (see above) 64 | DBObject query = null; 65 | // TODO use this query, combined with the "fields" selector, to get a list of result documents without address subdocument 66 | DBCursor results = null; 67 | 68 | // Then 69 | assertThat(results.size(), is(1)); 70 | DBObject theOnlyResult = results.next(); 71 | assertThat((String) theOnlyResult.get("_id"), is(charlie.getId())); 72 | assertThat((String) theOnlyResult.get("name"), is(charlie.getName())); 73 | assertThat(theOnlyResult.get("address"), is(nullValue())); 74 | assertThat((List) theOnlyResult.get("books"), is(charlie.getBookIds())); 75 | } 76 | 77 | @Before 78 | public void setUp() throws UnknownHostException { 79 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 80 | database = mongoClient.getDB("Examples"); 81 | collection = database.getCollection("people"); 82 | } 83 | 84 | @After 85 | public void tearDown() { 86 | database.dropDatabase(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise7QueryOperatorsTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mechanitis.mongodb.gettingstarted.person.Address; 4 | import com.mechanitis.mongodb.gettingstarted.person.Person; 5 | import com.mechanitis.mongodb.gettingstarted.person.PersonAdaptor; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.DBCursor; 9 | import com.mongodb.DBObject; 10 | import com.mongodb.MongoClient; 11 | import com.mongodb.MongoClientURI; 12 | import org.junit.After; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import java.net.UnknownHostException; 17 | 18 | import static java.util.Arrays.asList; 19 | import static org.hamcrest.CoreMatchers.is; 20 | import static org.junit.Assert.assertThat; 21 | 22 | public class Exercise7QueryOperatorsTest { 23 | private DB database; 24 | private DBCollection collection; 25 | 26 | @Test 27 | public void shouldReturnADBObjectWithAPhoneNumberLessThan1000000000() { 28 | // Given 29 | Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74)); 30 | collection.insert(PersonAdaptor.toDBObject(charlie)); 31 | 32 | Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 987654321), asList(27464, 747854)); 33 | collection.insert(PersonAdaptor.toDBObject(bob)); 34 | 35 | // When 36 | //TODO build up a query which checks the numeric value 37 | DBObject query = null; 38 | // TODO use this query to get a List of matching Documents from the database 39 | DBCursor results = null; 40 | 41 | // Then 42 | assertThat(results.size(), is(1)); 43 | assertThat((String) results.next().get("_id"), is(bob.getId())); 44 | } 45 | 46 | @Before 47 | public void setUp() throws UnknownHostException { 48 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 49 | database = mongoClient.getDB("Examples"); 50 | collection = database.getCollection("people"); 51 | } 52 | 53 | @After 54 | public void tearDown() { 55 | database.dropDatabase(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise8SkipAndLimitTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mongodb.BasicDBObject; 4 | import com.mongodb.DB; 5 | import com.mongodb.DBCollection; 6 | import com.mongodb.DBCursor; 7 | import com.mongodb.MongoClient; 8 | import com.mongodb.MongoClientURI; 9 | import org.junit.After; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | import java.net.UnknownHostException; 14 | 15 | import static org.hamcrest.CoreMatchers.is; 16 | import static org.junit.Assert.assertThat; 17 | 18 | public class Exercise8SkipAndLimitTest { 19 | private DB database; 20 | private DBCollection collection; 21 | 22 | @Test 23 | public void shouldReturnDBObjects3to9Of20DBObjectsUsingSkipAndLimit() { 24 | // Given 25 | for (int i = 0; i < 20; i++) { 26 | collection.insert(new BasicDBObject("name", "person" + i).append("someIntValue", i)); 27 | } 28 | 29 | // When 30 | // TODO no need for a query, just combine the find with the other operators available 31 | DBCursor results = null; 32 | 33 | // Then 34 | assertThat(results.size(), is(7)); 35 | assertThat((int) results.next().get("someIntValue"), is(3)); 36 | assertThat((int) results.next().get("someIntValue"), is(4)); 37 | assertThat((int) results.next().get("someIntValue"), is(5)); 38 | assertThat((int) results.next().get("someIntValue"), is(6)); 39 | assertThat((int) results.next().get("someIntValue"), is(7)); 40 | assertThat((int) results.next().get("someIntValue"), is(8)); 41 | assertThat((int) results.next().get("someIntValue"), is(9)); 42 | } 43 | 44 | @Before 45 | public void setUp() throws UnknownHostException { 46 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 47 | database = mongoClient.getDB("Examples"); 48 | collection = database.getCollection("people"); 49 | } 50 | 51 | @After 52 | public void tearDown() { 53 | database.dropDatabase(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/Exercise9IndexTest.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted; 2 | 3 | import com.mongodb.BasicDBObject; 4 | import com.mongodb.DB; 5 | import com.mongodb.DBCollection; 6 | import com.mongodb.DBObject; 7 | import com.mongodb.MongoClient; 8 | import com.mongodb.MongoClientURI; 9 | import org.junit.After; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | import java.net.UnknownHostException; 14 | 15 | import static org.hamcrest.CoreMatchers.is; 16 | import static org.junit.Assert.assertThat; 17 | import static org.junit.Assert.assertTrue; 18 | 19 | public class Exercise9IndexTest { 20 | private DB database; 21 | private DBCollection collection; 22 | 23 | @Test 24 | public void shouldCreateAnAscendingIndex() { 25 | // given 26 | collection.insert(new BasicDBObject("fieldToIndex", "Bob")); 27 | 28 | // when 29 | // TODO: added the index to the collection 30 | 31 | // then 32 | DBObject indexKey = (DBObject) collection.getIndexInfo().get(1).get("key"); 33 | assertTrue(indexKey.keySet().contains("fieldToIndex")); 34 | assertThat((Integer) indexKey.get("fieldToIndex"), is(1)); 35 | assertThat((String) collection.getIndexInfo().get(1).get("name"), is("fieldToIndex_1")); 36 | } 37 | 38 | @Before 39 | public void setUp() throws UnknownHostException { 40 | MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); 41 | database = mongoClient.getDB("Examples"); 42 | collection = database.getCollection("people"); 43 | } 44 | 45 | @After 46 | public void tearDown() { 47 | database.dropDatabase(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/person/Address.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted.person; 2 | 3 | public class Address { 4 | private final String street; 5 | private final String town; 6 | private final int phone; 7 | 8 | public Address(final String street, final String town, final int phone) { 9 | this.street = street; 10 | this.town = town; 11 | this.phone = phone; 12 | } 13 | 14 | public String getStreet() { 15 | return street; 16 | } 17 | 18 | public String getTown() { 19 | return town; 20 | } 21 | 22 | public int getPhone() { 23 | return phone; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/person/Person.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted.person; 2 | 3 | import java.util.List; 4 | 5 | public class Person { 6 | private final String id; 7 | private final String name; 8 | private final Address address; 9 | private final List bookIds; 10 | 11 | public Person(final String id, final String name, final Address address, final List bookIds) { 12 | this.id = id; 13 | this.name = name; 14 | this.address = address; 15 | this.bookIds = bookIds; 16 | } 17 | 18 | //getters and setters 19 | public String getId() { 20 | return id; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public Address getAddress() { 28 | return address; 29 | } 30 | 31 | public List getBookIds() { 32 | return bookIds; 33 | } 34 | 35 | 36 | //useful for testing 37 | 38 | @Override 39 | public String toString() { 40 | return "Person{" 41 | + "id='" + id + '\'' 42 | + ", name='" + name + '\'' 43 | + ", address=" + address 44 | + ", bookIds=" + bookIds 45 | + '}'; 46 | } 47 | 48 | @Override 49 | public boolean equals(final Object o) { 50 | if (this == o) { 51 | return true; 52 | } 53 | if (o == null || getClass() != o.getClass()) { 54 | return false; 55 | } 56 | 57 | Person person = (Person) o; 58 | 59 | if (!address.equals(person.address)) { 60 | return false; 61 | } 62 | if (!bookIds.equals(person.bookIds)) { 63 | return false; 64 | } 65 | if (!id.equals(person.id)) { 66 | return false; 67 | } 68 | if (!name.equals(person.name)) { 69 | return false; 70 | } 71 | 72 | return true; 73 | } 74 | 75 | @Override 76 | public int hashCode() { 77 | int result = id.hashCode(); 78 | result = 31 * result + name.hashCode(); 79 | result = 31 * result + address.hashCode(); 80 | result = 31 * result + bookIds.hashCode(); 81 | return result; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/test/java/com/mechanitis/mongodb/gettingstarted/person/PersonAdaptor.java: -------------------------------------------------------------------------------- 1 | package com.mechanitis.mongodb.gettingstarted.person; 2 | 3 | import com.mongodb.DBObject; 4 | 5 | /** 6 | * This Adaptor allows us to separate our domain object, Person, from our library-specific classes, in this case the MongoDB-specific 7 | * DBObject. 8 | */ 9 | public final class PersonAdaptor { 10 | public static final DBObject toDBObject(Person person) { 11 | throw new UnsupportedOperationException("You need to implement this"); 12 | } 13 | } 14 | --------------------------------------------------------------------------------