Spring Data MongoTemplate CRUD Operations

Learn how to use MongoTemplate to create, read, update and delete (CRUD) documents in MongoDB, using the insert, find, update and remove methods.

Example Details

The example shows how to:

Use MongoOperations to perform CRUD operations on the database.

  • Create a document using the insert method.
  • Read a document using the findAll, findById, findOne and find methods.
  • Update a document using updateFirst.
  • Delete a document using remove.
  • Set up a MongoTemplate using Java configuration.

MongoTemplate

The MongoTemplate class implements the MongoOperations interface. This is the preferred way to reference the operations on MongoTemplate.

insert converts an object or a collection of objects to the MongoDB native representation and adds it to a collection.

findAll returns all the objects of the specified type.

findById returns a document with the given id.

find returns the results of an ad-hoc query.

findOne does the same but only returns the first object.

updateFirst updates the first object that matches the query document with the provided update document.

remove deletes all documents from the collection that match the provided query document criteria.

Crud.java
package io.lishman.springdata.template;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import io.lishman.springdata.config.MongoConfig;
import io.lishman.springdata.domain.Continent;
import io.lishman.springdata.domain.Country;

@Component
public class Crud {
    
    @Autowired private MongoOperations mongoOps;
    
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfig.class);
        Crud crud = ctx.getBean(Crud.class);
        crud.useMongoTemplateForCrud();
        ctx.close();
    }
    
    private void useMongoTemplateForCrud() {

        //------------------------------------------------- create

        if (mongoOps.collectionExists(Country.class)) {
            mongoOps.dropCollection(Country.class);
        }
        
        Country vietnam = new Country("Vietnam", 128565, 90388000L, new Continent(2, "Asia"));
        mongoOps.insert(vietnam);

        Country[] countries = new Country[] {
            new Country("Greece", 50949, 11257285L, new Continent(3, "Europe")),
            new Country("Iceland", 39770, 321857L, new Continent(3, "Europe")),
            new Country("New Zealand", 104454, 4320300L, new Continent(6, "Australia")),
            new Country("Serbia", 34116, 7120666L, new Continent(3, "Europe"))
        };
        
        mongoOps.insert(Arrays.asList(countries), Country.class);
        
        //------------------------------------------------- read
        
        List<Country> allCountries = mongoOps.findAll(Country.class);
        
        BigInteger newZealandId = allCountries.get(3).getId();
        Country newZealand = mongoOps.findById(newZealandId, Country.class);
        
        Query europeanQuery = query(where("continent.name").is("Europe"));
        List<Country> europeanCountries = mongoOps.find(europeanQuery, Country.class);
        
        Country greece = mongoOps.findOne(query(where("name").is("Greece")), Country.class);
        
        //------------------------------------------------- update
        
        Query query = query(where("name").is("Serbia"));
        Update update = update("population", 7120777L);
        mongoOps.updateFirst(query, update, Country.class);
        
        //------------------------------------------------- delete
        
        mongoOps.remove(query(where("_id").is("3")), Continent.class);
    }

}

MongoOperations

The implementation for MongoOperations is provided by the thread-safe MongoTemplate.

This class is registered as a Spring bean and injected into our application as required.

MongoConfig.java
package io.lishman.springdata.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import io.lishman.springdata.repository.RepositoryPackage;
import io.lishman.springdata.template.TemplatePackage;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;

@Configuration
@EnableMongoRepositories(basePackageClasses=RepositoryPackage.class)
@ComponentScan(basePackageClasses=TemplatePackage.class)
public class MongoConfig extends AbstractMongoConfiguration {
    
    // ---------------------------------------------------- mongodb config

    @Override
    protected String getDatabaseName() {
        return "world";
    }

    @Override
    @Bean
    public MongoClient mongo() throws Exception {
        MongoClient client = new MongoClient("mongo");
        client.setWriteConcern(WriteConcern.SAFE);
        return client;
    }

    @Override
    protected String getMappingBasePackage() {
        return "io.lishman.springdata.domain";
    }
    
    // ---------------------------------------------------- MongoTemplate
    
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongo(), getDatabaseName());
    }
    
}