How to findOneAndDelete in mongodb using MongoRepository in Spring - java

I am using a Spring web service and MongoDb to hold my data. Currently my Repository class extends MongoRepository and an obj of its interface gets injected into my Controller.
There is no method for finding and deleting a specific entity in the MongoRepository interface. How can I do this without having to provide a concrete implementation? I need to do the operation at the same time.
Here's my code on github if its useful: https://github.com/RyanNewsom/DentistAppointmentSchedulerService

I ended up figuring this one out. I made a custom class and used MongoTemplate. You can then submit a query using mongoTemplate. It contains a lot more mongo specific implementation.
#Repository
public class AppointmentCustomRepository {
#Autowired
MongoTemplate mongoTemplate;
public Appointment getAppointmentAndDelete(String id) {
return mongoTemplate.findAndRemove(Query.query(Criteria.where("id").is(id)), Appointment.class);
}
}

Sample snippet to find and delete one document in Mongo DB using Java API's
MongoCollection<Document> collection = database.getCollection("PasstheCollectionName");
Document document = collection.find.first();
Object value = document.get("_id");
Bson filter = Filter.and(Filter.eq("_id",value));
collection.findOneAndDelete(filter);

Related

Spring boot - $sample doesn't work on #Aggregation annotation

I have the following method in a MongoDB Repository interface
#org.springframework.stereotype.Repository
public interface AnecdoteRepository extends org.springframework.data.mongodb.repository.MongoRepository<Anecdote, Long> {
#Aggregation(pipeline = { "{$sample:{size: 1}}" })
Optional<Anecdote> findRandom();
}
I have 20 records on Anecdote collection, but when I call directly this method, it returns me an empty Optional.
However, I have the same aggregation on MongoDB Compass and it returns me an only record, as I want.
Aggregation structure
Result
Should I add more records? Or what's wrong with the first pipeline in aggregation?
I'm using spring-boot-starter-data-mongodb library

How to create mongodb collection in spring boot without using pojo class?

I have a spring boot app with a MongoDB connection. On using the POJO/Model class with #Document(Collection = "CompanyDetails"), it successfully creates the collection in MongoDB after "POSTMAPPING" and the result goes inside the CompanyDetails collection as expected.
I have used controller, service, repository, and used the Map<String, Object> in parenthesis of the repository rather than using POJO class.
Controller:
#PostMapping("/addRecords")
public Map<String, Object> addCompanyDetails(#RequestBody Map<String, Object> companyDetails) {
return companyDetailsService.addCompanyDetails(companyDetails);
}
Service:
#Service
public class CompanyDetailsService {
#Autowired
CompanyDetailsRepository companyDetailsRepository;
public Map<String, Object> addCompanyDetails(Map<String, Object> companyDetails) {
return companyDetailsRepository.insert(companyDetails);
}
}
Repository:
#Repository
public interface CompanyDetailsRepository extends MongoRepository<Map<String, Object>, String> {}
My requirement is to create a collection without a POJO class. Because, the fields are not fixed(while inserting records). So, I can't declare fields in the POJO class & generate a getter setter.
As I'm not using the POJO class, when I POST record, it creates a collection with the name "map" & insert records inside that.
But, expected was to create "CompanyDetails" collection & store data inside that.
Yes, people using MongoDB faced this issue as MongoDB is a schemaless database and creating POJO will be difficult. So, here is the solution for such use-cases.
Firstly, you can use the MongoClient to connect with your database. Check out this document for your reference: Connect to MongoDB
Secondly, you can create databases and collections using that `mongoClient object. Check out this document for your reference Create database and collection
Finally, you can use some generic objects like HashMap or BasicDBObject to perform your CRUD operation

How to render data from multiple tables from MySQL using React, Spring Boot?

I have four tables in a database. When the user uses the Search option from the React application I want the search button to query all the tables and display data from all the tables which is AWS RDS MYSQL. How should I proceed? I am using Spring boot, mysql, and react.
I would recommend taking a look at JPA Respositories. Since your db seams to be small, a simple repository method like that one should make the trick.
However, if you have a more complicated requirement, you can use a Spring Projection. Create a query that retrieves all the fields you'll need, even if they're from different tables, and map the result into a Spring Projection
Using spring data jpa you should create a method in your repository that returns a list of your projection class:
public interface MyRepository extends Repository<MyEntityProjection, Long> {
#Query("SELECT ... WHERE field = ?1")
List<MyEntityProjection> getData(String param);
}
The projection class should be something like this:
public interface MyEntityProjection {
String getField();
String getField2();
}
Adding as many fields as your query returns.
Read the docs I linked for more information and examples.

How to make serverStatus() query via spring data in mongoDb

I got database with several collections in micorservice, so there's controllers which works fine. But I need to collect statistics from servers, including database. There's a good query serverStats() which gives all the information about the server, but how can I pass it through app layers?
I made interface repository extended ReactiveCrudRepository using SomeModel class as a place holder and wrote one method like String getStatistics() with #Query annotation, but it doesn't work
public interface MongoMonitoring extends ReactiveCrudRepository<SomeModel, String> {
#Query("{ serverStatus: 1 }")
String getStatus();
Use MongoTemplate. The code like:
private MongoTemplate mongoTemplate;
Document result = this.mongoTemplate.executeCommand("{ serverStatus: 1 }");
The document is from package org.bson.Document which is like JSON.

Change default behaviour of mongoTemplate.find

Is there any way to modify every query prepared by mongotemplate.find spring boot 2?
I want to modify every find query prepared by spring data mongo find . I want to add custom query after every find query to mongo.
How can I achieve that in spring boot 2.
I want to override find methods of mongo template with my own implementation and want to add some custom query on top of find query which was built by crud repository methods.
I want to add some custom query by overriding methods of mongotemplate to every find method of crud repository
you would need to customize the repository class implementation for the mongoDB.
below is the sample code to help you understand how to add customized query in the repository. you would need to twik the code as per your requirement after getting the result.
public interface PersonRepository extends PagingAndSortingRepository<Person, String> {
List<Person> findByLastname(String lastname);
Page<Person> findByFirstname(String firstname, Pageable pageable);
Person findByShippingAddresses(Address address);
}
you can visit this page for proper understanding
https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mongo.repositories.html

Categories

Resources