[英]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. 我正在构建一个应用程序,该程序将处理将大量数据插入各种集合中,然后稍后从mongodb数据库中读取它们。 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'成功地将数据插入到所需的没有实体类的集合中。
mongotemplate.insert(map,"mycollection"); mongotemplate.insert(map,“ mycollection”);
mongotemplate.find(query,myentity.class, "mycollection"); mongotemplate.find(query,myentity.class,“ mycollection”);
I would like a method like: mongotemplate.find(query, "mycollection"); 我想要一种方法:mongotemplate.find(query,“ mycollection”);
There's an example here: 这里有一个例子:
https://www.baeldung.com/queries-in-spring-data-mongodb 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. 还有其他按方法查找的方法,findOne,findById等,取决于哪种情况适合您的用例。
If you don't want to use mongotemplate, you would need to use BasicDBObject to achieve this. 如果您不想使用mongotemplate,则需要使用BasicDBObject来实现。
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: 您将使用的依赖项是最新版本的mongo java驱动程序:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.11.0</version>
</dependency>
Take a look at MongoDB Java driver . 看一下MongoDB Java驱动程序 。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.