简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM