0

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.

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.