Spring Data MongoDB – Save Or Update

By | August 31, 2018

In this tutorial you will learn how to save or update data into database using spring data mongoDB.

Spring Data MongoDB – Save Or Update

First declare “Mongo Template”, then do save or update :

@Autowired
private MongoTemplate mongoTemplate;

Spring Data MongoDB – Save Or UpdateMongo Template Save

User user = new User();
user.setName(“cimblo”);
user.setAge(99);
//save data with save() function
mongoTemplate.save(userTest1);

Mongo Template Update

No need to find the document. Just declare the Query with Criteria, then modify and update it with updateFirst() method.

String TABLE_USER = “table_user”;
Query query = new Query();
query.addCriteria(Criteria.where("name").is(“cimblo”);
Update update = new Update();
update.set(“age”, 25);
update.set(“updatedDate”, new Date());
mongoTemplate.updateFirst(query, update, TABLE_USER);

Update result:

{ 
	"_id" : ObjectId("id"), 
	"name" : “cimblo”, 
	"age" : 20, 
	"createdDate" : ISODate("2013-04-06T23:17:35.530Z"), 
	“updatedDate" : ISODate("2013-04-06T23:17:35.530Z") 
}

But using spring data mongoDB is very simple, you can just like this with mongo repository:

You can Save Or Update the whole object, if “_id” is present, perform an update, else insert it. If using mongo repository like below:

Using MongoRepository – Save OR Update

@Autowire
UserRepository userRepository;

//Find the document first by USER ID
User user = userRepository.findOne(id);

if (user == null) {
  User user = new User();
  user.setName(“Your Name”);
  user.setAge(20);
  //save new user object
  userRepository.save(user);
} else {
  user.setName(“Your Name”);
  user.setAge(20);
  //update
  userRepository.save(user);
}

That’s it 🙂

Need more reference? you can goto:

2 thoughts on “Spring Data MongoDB – Save Or Update

  1. Pingback: Spring Data MongoDB - Upsert ~ Cimblo.com

  2. Pingback: Allow Remote Access On MongoDB ~ Cimblo.com

Leave a Reply

Your email address will not be published. Required fields are marked *