{"id":24617638,"url":"https://github.com/pacphi/spring-boot-mongodb-example","last_synced_at":"2025-03-18T21:26:59.926Z","repository":{"id":48480922,"uuid":"117278844","full_name":"pacphi/spring-boot-mongodb-example","owner":"pacphi","description":"Spring Boot + Spring Data Mongo / REST example","archived":false,"fork":false,"pushed_at":"2021-07-23T13:18:26.000Z","size":69,"stargazers_count":0,"open_issues_count":4,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-01-24T23:39:36.625Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pacphi.png","metadata":{"files":{"readme":"README.adoc","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-01-12T19:14:32.000Z","updated_at":"2019-05-03T00:42:55.000Z","dependencies_parsed_at":"2022-09-13T15:24:34.924Z","dependency_job_id":null,"html_url":"https://github.com/pacphi/spring-boot-mongodb-example","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pacphi%2Fspring-boot-mongodb-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pacphi%2Fspring-boot-mongodb-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pacphi%2Fspring-boot-mongodb-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pacphi%2Fspring-boot-mongodb-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pacphi","download_url":"https://codeload.github.com/pacphi/spring-boot-mongodb-example/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244308659,"owners_count":20432246,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-01-24T23:39:45.664Z","updated_at":"2025-03-18T21:26:59.901Z","avatar_url":"https://github.com/pacphi.png","language":"Java","readme":"---\ntags: [spring-data, mongodb]\nprojects: [spring-data-mongodb]\n---\n:toc:\n:icons: font\n:source-highlighter: prettify\n:project_id: gs-accessing-data-mongodb\nThis guide walks you through the process of using http://projects.spring.io/spring-data-mongodb/[Spring Data MongoDB] to build an application that stores data in and retrieves it from http://www.mongodb.org/[MongoDB], a document-based database.\n\n\n== What you'll build\n\nYou will store `Customer` link:/understanding/POJO[POJOs] in a MongoDB database using Spring Data MongoDB.\n\n== What you'll need\n\n:java_version: 1.8\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/prereq_editor_jdk_buildtools.adoc[]\n\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/how_to_complete_this_guide.adoc[]\n\n\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-gradle.adoc[]\n\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-maven.adoc[]\n\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-sts.adoc[]\n\n[[initial]]\n== Install and launch MongoDB\nWith your project set up, you can install and launch the MongoDB database.\n\n\nIf you are using a Mac with homebrew, this is as simple as:\n\n    $ brew install mongodb\n\nWith MacPorts:\n\n    $ port install mongodb\n\nFor other systems with package management, such as Redhat, Ubuntu, Debian, CentOS, and Windows, see instructions at http://docs.mongodb.org/manual/installation/.\n\nAfter you install MongoDB, launch it in a console window. This command also starts up a server process.\n\n\n    $ mongod\n\nYou probably won't see much more than this:\n\n....\nall output going to: /usr/local/var/log/mongodb/mongo.log\n....\n\n== Define a simple entity\nMongoDB is a NoSQL document store. In this example, you store `Customer` objects.\n\n`src/main/java/io/pivotal/customer/Customer.java`\n[source,java]\n----\ninclude::complete/src/main/java/io/pivotal/customer/Customer.java[]\n----\n\nHere you have a `Customer` class with three attributes, `id`, `firstName`, and `lastName`. The `id` is mostly for internal use by MongoDB. You also have a single constructor to populate the entities when creating a new instance.\n\n\nNOTE: In this guide, the typical getters and setters have been left out for brevity.\n\n`id` fits the standard name for a MongoDB id so it doesn't require any special annotation to tag it for Spring Data MongoDB.\n\nThe other two properties, `firstName` and `lastName`, are left unannotated. It is assumed that they'll be mapped to fields that share the same name as the properties themselves.\n\n\nThe convenient `toString()` method will print out the details about a customer.\n\nNOTE: MongoDB stores data in collections. Spring Data MongoDB will map the class `Customer` into a collection called _customer_. If you want to change the name of the collection, you can use Spring Data MongoDB's http://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/mapping/Document.html[`@Document`] annotation on the class.\n\n\n== Create simple queries\nSpring Data MongoDB focuses on storing data in MongoDB. It also inherits functionality from the Spring Data Commons project, such as the ability to derive queries. Essentially, you don't have to learn the query language of MongoDB; you can simply write a handful of methods and the queries are written for you.\n\n\nTo see how this works, create a repository interface that queries `Customer` documents.\n\n`src/main/java/io/pivotal/customer/CustomerRepository.java`\n[source,java]\n----\ninclude::complete/src/main/java/io/pivotal/customer/CustomerRepository.java[]\n----\n\n`CustomerRepository` extends the `MongoRepository` interface and plugs in the type of values and id it works with: `Customer` and `String`. Out-of-the-box, this interface comes with many operations, including standard CRUD operations (create-read-update-delete).\n\nYou can define other queries as needed by simply declaring their method signature. In this case, you add `findByFirstName`, which essentially seeks documents of type `Customer` and finds the one that matches on `firstName`.\n\nYou also have `findByLastName` to find a list of people by last name.\n\nIn a typical Java application, you write a class that implements `CustomerRepository` and craft the queries yourself. What makes Spring Data MongoDB so useful is the fact that you don't have to create this implementation. Spring Data MongoDB creates it on the fly when you run the application.\n\nLet's wire this up and see what it looks like!\n\n== Create an Application class\nHere you create an Application class with all the components.\n\n`src/main/java/io/pivotal/Application.java`\n[source,java]\n----\ninclude::complete/src/main/java/io/pivotal/Application.java[]\n----\n\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/spring-boot-application.adoc[]\n\nSpring Boot will handle those repositories automatically as long as they are included\nin the same package (or a sub-package) of your `@SpringBootApplication` class. For more control over the\nregistration process, you can use the `@EnableMongoRepositories` annotation.\n\nNOTE: By default, `@EnableMongoRepositories` will scan the current package for any interfaces that extend one of Spring Data's repository interfaces. Use it's `basePackageClasses=MyRepository.class` to safely tell Spring Data MongoDB to scan a different root package by type if your project layout has multiple projects and its not finding your repositories.\n\nSpring Data MongoDB uses the `MongoTemplate` to execute the queries behind your `find*` methods. You can\nuse the template yourself for more complex queries, but this guide doesn't cover that.\n\n`Application` includes a `main()` method that autowires an instance of `CustomerRepository`: Spring Data\nMongoDB dynamically creates a proxy and injects it there. We use the `CustomerRepository` through a few\ntests. First, it saves a handful of `Customer` objects, demonstrating the `save()` method and setting\nup some data to work with. Next, it calls `findAll()` to fetch all `Customer` objects from the database.\nThen it calls `findByFirstName()` to fetch a single `Customer` by her first name. Finally, it calls\n`findByLastName()` to find all customers whose last name is \"Smith\".\n\nNOTE: Spring Boot by default attempts to connect to a locally hosted instance of MongoDB. Read the http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-mongodb[reference docs] for details on pointing your app to an instance of MongoDB hosted elsewhere.\n\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_mainhead.adoc[]\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_with_both.adoc[]\n\n\nAs our `Application` implements `CommandLineRunner`, the `run` method is invoked automatically when boot\nstarts. You should see something like this (with other stuff like queries as well):\n....\n== Customers found with findAll():\nCustomer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']\nCustomer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']\n\n== Customer found with findByFirstName('Alice'):\nCustomer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']\n== Customers found with findByLastName('Smith'):\nCustomer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']\nCustomer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']\n....\n\n\n== Connecting to an external Mongo instance\n\nIf you wanted to connect to a Mongo instance on Azure, you could add (though not recommended) an `application-cloud.yml` file to `src/main/resources` containing, e.g.,\n\n```\nspring:\n  data:\n    mongodb:\n      uri: mongodb://{username}:{password}@{host}.mlab.com:46267/{database-name}\n\nmanagement:\n  cloudfoundry:\n    enabled: true\n    skip-ssl-validation: true\n```\n\nHost a free 500mb instance of Mongo available on AWS, GCP or Azure @ https://mlab.com!\n\n== Summary\nCongratulations! You set up a MongoDB server and wrote a simple application that uses Spring Data MongoDB to save objects to and fetch them from a database -- all without writing a concrete repository implementation.\n\nNOTE: If you're interesting in exposing MongoDB repositories with a hypermedia-based RESTful front end with little effort, you might want to read link:/guides/gs/accessing-mongodb-data-rest[Accessing MongoDB Data with REST].\n\n== See Also\n\nThe following guides may also be helpful:\n\n* https://spring.io/guides/gs/accessing-data-jpa/[Accessing Data with JPA]\n* https://spring.io/guides/gs/accessing-data-gemfire/[Accessing Data with Gemfire]\n* https://spring.io/guides/gs/accessing-data-mysql/[Accessing data with MySQL]\n* https://spring.io/guides/gs/accessing-data-neo4j/[Accessing Data with Neo4j]\n\ninclude::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/footer.adoc[]\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpacphi%2Fspring-boot-mongodb-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpacphi%2Fspring-boot-mongodb-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpacphi%2Fspring-boot-mongodb-example/lists"}