Documentos de Académico
Documentos de Profesional
Documentos de Cultura
En este tutorial paso a paso veremos como configurar tu servidor con MongoDB en forma
segura. También aprenderás a crear bases de datos y usuarios con permisos específicos.
Finalmente veremos como conectarnos en forma remota.
1
Habilitar el puerto 20017 en el firewall
Para mayor seguridad, el puerto utilizado por MongoDB en tu Cloud Server es el 20017.
Por defecto este se encuentra cerrado a nivel de firewall. Para abrir el acceso ingresa en la
Configuración de tu cloud server y luego en la pestaña Firewall. Una vez allí crea una
regla que permita el acceso de conexiones externas al puerto 20017.
Si desconoces cuales son las IPs desde las cuales, tu o tu aplicación, se conectarán al
servidor de MongoDB, utiliza 0.0.0.0/0. Así permitirás que cualquier IP pueda conectarse a
MongoDB. Sin embargo, te recomendamos crear reglas con las IPs (o rango de IP’s)
específicas para brindarle mayor seguridad a tus bases de dato.
2
Verificar la versión de MongoDB
Accede a través de la consola SSH a tu servidor y verifica la versión de MongoDB con el
siguiente comando:
1mongod --version
Conocer la versión te servirá más adelante si es que decides utilizar un cliente con interfaz
gráfica para administrar tus bases de datos y usuarios, ya que no todas tienen soporte para
las últimas versiones de MongoDB.
3
Crear un usuario administrador
Nuevamente a través de la consola SSH y utilizando los siguientes comandos, creamos un
usuario con los permisos necesarios para administrar cualquier base de datos del servidor
MongoDB.
1
2 mongo --port 20017
3
use admin
4
5 db.createUser(
6 {
7 user: "myServerAdmin",
8 pwd: "mipassword",
9 } roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
10);
11
Cambia los datos “user” y “pwd” del código de arriba, con el usuario y contraseña que
decidas utilizar.
4
Restringir el acceso No Autenticado
Por defecto, es posible acceder al servidor de MongoDB sin necesidad de autenticarse y
esto genera problemas de seguridad. Ahora que ya disponemos de un usuario con los
privilegios suficientes, cambiaremos la configuración para restringir el acceso mediante
autenticación.
1mcedit /etc/mongod.conf
Una vez guardado el cambio, reiniciamos el servicio de MongoDB para que los mismos
hagan efecto.
5
Crear una Base de Datos y un usuario para la misma
Llegó el momento esperado, el de crear la base de datos que utilizaremos para nuestra
aplicación. A diferencia de servidores como MySQL donde hay un comando explícito para
crearlas, en MongoDB las base de datos se crean insertando el primer contenido (una
colección) o creando un usuario para la misma.
En nuestro caso crearemos un base de datos llamada test agregándole un usuario llamado
myDbAdmin.
1
use test
2
3db.createUser(
4 {
5 user: "myDbAdmin",
6 pwd: "mipassword",
7 roles: [ { role: "readWrite", db: "test" } ]
}
8);
9
Ahora, para acceder a la base de datos recién creada utilizamos el siguiente comando:
1use test
2
3db.personal.save({nombre:'Ariel Perez',edad:23})
4db.personal.save({nombre:'Diego Angel',edad:32})
5db.personal.find()
7
Aprovechar una interfaz gráfica
Si bien la consola MongoShell nos permite hacer prácticamente de todo con nuestro
MongoDB, utilizar interfaces gráficas en la administración de bases de datos simplifica
mucho la tarea.
1mongodb://usuario:password@host:puerto/nombre_db
1mongodb://myDbAdmin:mipassword@200.58.96.113:20017/test
REST API: Java Spring Boot
and MongoDB
Creating a RESTful web service using the Spring Boot framework and MongoDB
Thomas Gleason
The Java Spring Boot framework provides a powerful set of tools for web development on
both the front-end and back-end. It has built-in configuration for security and database
access, as well as simple request mappings. This framework is highly configurable and
makes web development extremely simple.
Why MongoDB?
Mongo is quickly growing in popularity among NoSQL databases. Read more about
NoSQL and its benefits here. MongoDB, specifically, is perfect for developing a REST
API with Spring Boot for a couple of key reasons:
1. Java
2. Spring Boot
3. Maven
4. MongoDB
5. Postman
This tutorial assumes that you already have an accessible instance of MongoDB that you
can connect to. For more information on getting started with MongoDB, visit their online
tutorial.
Let us start by creating a test database. I will call mine “rest_tutorial” using the following
command in the MongoDB shell, or through a database manager like MongoDB Compass:
use rest_tutorial;
This will create a new database in MongoDB that we can use for our tutorial.
db.createCollection(“pets”);
Once the collection is created, we need to add some data! This collection will hold the
names, breeds, and species of various pets, so a single document would be formatted as
follows:
{
“name” : “Spot”,
“species” : “dog”,
“breed” : “pitbull”
}
db.pets.insertMany([
{
“name” : “Spot”,
“species” : “dog”,
“breed” : “pitbull”
},
{
“name” : “Daisy”,
“species” : “cat”,
“breed” : “calico”
},
{
“name” : “Bella”,
“species” : “dog”,
“breed” : “australian shepard”
}
]);
Spring offers a tool called the Spring Initializr to help jump-start your Spring Boot
project. Access the Initializr at start.spring.io, and enter the following information:
Then click Generate Project to download a .zip file with the basic project structure.
With the project downloaded from the Spring Initializr, you can now open it in your
favorite IDE to begin editing the project. First, we will want to add a pets model, so that
Spring will know what kind of data the database will return. We can do this by creating a
new folder in src/main/java/[package name]/ called “models”. In the new “models”
folder, we can create a file called Pets.java. This Java class will hold the basic structure
of a document in the “pets” collection, so the class looks as follows
package com.example.gtommee.rest_tutorial.models;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
public class Pets {
@Id
public ObjectId _id;
// Constructors
public Pets() {}
The @Id annotation tells spring that the _id field will be used as the primary identifier. The
rest of the class contains the basic constructors, getters, and setters for the Pets object.
Now that we have a model that identifies the data structure stored in the database to Spring
Boot, we can create the connector between the model and MongoDB. This is done through
a Repository interface. We can create this first by making a new folder called “repositories”
in src/main/java/[package name]/.
In the new “repositories” folder, we can create a file called PetsRepository.java. The
name of this repository is extremely important because it tells MongoDB the collection that
it will be querying (in this case, the pets collection). This interface will extend the
MongoRepository class, which already contains generic methods like save (for
creating/updating documents) and delete (for removing documents), but we will need to
specify additional methods ourselves.
Luckily, we do not need to manually implement these queries, we can simply use Spring
Boot’s repository naming conventions, and the MongoRepository will intelligently
construct the queries at runtime. This means that our interface will be extremely simple, as
follows:
package com.example.gtommee.rest_tutorial.repositories;
import com.example.gtommee.rest_tutorial.models.Pets;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PetsRepository extends MongoRepository<Pets, String> {
Pets findBy_id(ObjectId _id);
}
Adding the MongoDB Connection Info
To tell Spring the connection information for our MongoDB, we will need to add conection
details to the application.properties file, located in the “src/main/resources” folder.
Add the following lines to the file, replacing the information in brackets with the
information specific to your MongoDB instance:
spring.data.mongodb.host=[host]
spring.data.mongodb.port=[port]
spring.data.mongodb.authentication-database=[authentication_database]
spring.data.mongodb.username=[username]
spring.data.mongodb.password=[password]
spring.data.mongodb.database=rest_tutorial
This is all the information that Spring will need to connect to the database.
Spring should now be able to connect to MongoDB, so now we can establish the enpoints
that we can contact to interact with the database. This will be done in a Spring Rest
Controller, which uses Request Mappings to map requests with functions. We can create a
Rest Controller by adding a file called PetsController.java to the
src/main/java/[package name]/ folder. The basic file structure will look as follows:
package com.example.gtommee.rest_tutorial;
import com.example.gtommee.rest_tutorial.models.Pets;
import com.example.gtommee.rest_tutorial.repositories.PetsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(“/pets”)
public class PetsController {
@Autowired
private PetsRepository repository;
}
The @RestController annotation tells Spring that this class will requested by URL and
will return data to the requester. The @RequestMapping annotation specifies the base URL
that the controller will be handling, so any request to the host starting with “/pets” will be
directed to this controller. The @Autowired annotation creates an instance of the
PetsRepository object that will allow us to access and modify the pets database.
All of the following enpoints will be added directly into the PetsController class.
GET
@RequestMapping(value = “/”, method = RequestMethod.GET)
public List<Pets> getAllPets() {
return repository.findAll();
}
@RequestMapping(value = “/{id}”, method = RequestMethod.GET)
public Pets getPetById(@PathVariable(“id”) ObjectId id) {
return repository.findBy_id(id);
}
The first mapping takes any GET requests to the host with a URL of /pets/ and maps them
to the getAllPets() method, which requests all documents from the pets collection.
The second mapping takes and GET requests to the host with a URL of /pets/ followed by
an ObjectId and maps them to the getPetById() method, which searches the pets
collection for the document with an _id field equal to the ObjectId in the URL.
PUT
@RequestMapping(value = “/{id}”, method = RequestMethod.PUT)
public void modifyPetById(@PathVariable(“id”) ObjectId id, @Valid
@RequestBody Pets pets) {
pets.set_id(id);
repository.save(pets);
}
This mapping expects a request body (in JSON format) with each of the fields that a Pets
object contains (name, species, and breed). The id in the request URL is the _id of the
document to be modified.
POST
@RequestMapping(value = “/”, method = RequestMethod.POST)
public Pets createPet(@Valid @RequestBody Pets pets) {
pets.set_id(ObjectId.get());
repository.save(pets);
return pets;
}
This mapping expects a request body (in JSON format) with each of the fields that a Pets
object contains (name, species, and breed), and assigns it a new ObjectId. This object is
then inserted into the pets collection, and the new Pets object is returned.
DELETE
@RequestMapping(value = “/{id}”, method = RequestMethod.DELETE)
public void deletePet(@PathVariable ObjectId id) {
repository.delete(repository.findBy_id(id));
}
This endpoint takes the _id of a document in the pets collection and removes that
document from the collection.
Completed Controller
package com.example.gtommee.rest_tutorial;
import com.example.gtommee.rest_tutorial.models.Pets;
import com.example.gtommee.rest_tutorial.repositories.PetsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(“/pets”)
public class PetsController {
@Autowired
private PetsRepository repository;
Now that the controller has all of our endpoints, we can begin testing our API! From the
command line, in the project root, run the `mvn spring-boot:run` command to compile the
code and start the Spring server with the default port 8080.
Once the server starts, you are free to test your API however you choose.
POST 'http://localhost:8080/pets'
Returns:
{
“_id”: “5aecef5b6d55754834124df3”,
“name”: “Liam”,
“species”: “cat”,
“breed”: “tabby”
}
PUT ‘http://localhost:8080/pets/5aecef5b6d55754834124df3
Returns:
empty response
GET ‘http://localhost:8080/pets/5aecef5b6d55754834124df3’
Returns:
{
“_id”: “5aecef5b6d55754834124df3”,
“name”: “Liam”,
“species”: “cat”,
“breed”: “siamese”
}
DELETE ‘http://localhost:8080/pets/5aecef5b6d55754834124df3’
Returns:
empty response
GET ‘http://localhost:8080/pets’
Returns:
[
{
“_id”: “5aeccb0a18365ba07414356c”,
“name”: “Spot”,
“species”: “dog”,
“breed”: “pitbull”
},
{
“_id”: “5aeccb0a18365ba07414356d”,
“name”: “Daisy”,
“species”: “cat”,
“breed”: “calico”
},
{
“_id”: “5aeccb0a18365ba07414356e”,
“name”: “Bella”,
“species”: “dog”,
“breed”: “australian shepard”
}
]
Future Articles
Now you have created a REST API using Java Spring Boot and MongoDB! In future
articles, I will explain how to add additional features to your API, such as authentication! I
will list the articles here as they become availible.