简体   繁体   中英

Is there a simple way for querying a specific document from a collection of a mongodb database using spring boot without entity/pojo classes?

I am building an application which would deal with inserting a large number of data into various collections and then reading them later from the mongodb database. Since the number of collections would increase a lot in future and the documents would also get new keys, I would like to implement my code without entity classes since they need to be updated and added each time when new collections/document changes are made.

I have successfully inserted data into the desired collection without entity classes by using 'MongoTemplate'.

mongotemplate.insert(map,"mycollection");

mongotemplate.find(query,myentity.class, "mycollection");

I would like a method like: mongotemplate.find(query, "mycollection");

There's an example here:

https://www.baeldung.com/queries-in-spring-data-mongodb

Query query = new Query();
query.addCriteria(Criteria.where("name").is("Eric"));
List<User> users = mongoTemplate.find(query, User.class);

There are other find by methods as well, findOne, findById etc, depends on which one fits your use case.

If you don't want to use mongotemplate, you would need to use BasicDBObject to achieve this.

DBCollection collection = database.getCollection("mycollection");
BasicDBObject query = new BasicDBObject();
query.put("mykey", "keyvalue");
DBCursor cursor = collection.find(query);

The dependency you would use is the mongo java driver with latest release version:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.11.0</version>
</dependency>

Take a look at MongoDB Java driver .

You can do something like this:

private List<Document> queryCollection(String collectionName) {
    final List<Document> results = new ArrayList<>();
    mongoDatabase.getCollection(collectionName).find(/*FILTER*/).into(results);
    return results;
}

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