java - 在Spring Boot JPA中没有定义bean的情况下从mongodb获取所有集合数据

标签 java mongodb spring-boot jpa collections

因为 mongo 集合中的字段是随着对象的不同而变化的。 object中有4个字段,other有8个字段,那么我们如何获取所有集合数据。

最佳答案

您可以使用 MongoDB Spring Data 的 MongoTemplate API方法如下所示。

可以使用

MongoTemplate 类的 findAll 方法。该方法要求指定entityClass。如果您没有定义实体类,则通用 org.bson.Document可以指定类(请参见下面的示例代码)。

public <T> List<T> `findAll`(Class<T> entityClass, String collectionName)

Query for a list of objects of type T from the specified collection.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of MappingMongoConverter will be used. If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way to map objects since the test for class type is done in the client and not on the server.

示例:

MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
List<Document> list = mongoOps.findAll(Document.class, "person");
list.forEach(doc -> System.out.println(doc.toJson()));

上面的代码中,读取了person集合;并且该集合包含不同领域的文档。对于输入文档:

{ "_id" : 1, "fld" : "str-1" }
{ "_id" : 3, "fld" : "str-3", "fld2" : 13 }
{ "_id" : 10, "dt" : ISODate("2020-03-07T03:08:49.855Z") }

输出为:

{"_id": 1.0, "fld": "str-1"}
{"_id": 3.0, "fld": "str-3", "fld2": 13.0}
{"_id": 10.0, "dt": {"$date": 1583550529855}}

关于java - 在Spring Boot JPA中没有定义bean的情况下从mongodb获取所有集合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60562666/

相关文章:

java - 在 grpc Spring boot 中关闭自定义线程池执行器

java - Spring Boot 禁用/错误映射

java - 使用自定义数据填充 listView,子类化 BaseAdapter(本主题中的示例)

mongodb - MongoDB 3.0.1 mongodump错误

arrays - Mongoose 查询,查找 B.array 中与 A.array 中匹配的所有 B 类型项目

node.js - 将文件流式传输到客户端后,永远不会发送 res.end()

mysql - 类型 : 8962101012749336481 的查询错误和结果错误值

Java:(int)(float)Float.valueOf(s) 或 Float.valueOf(s).toInt()

java - 为什么这个方法的时间复杂度是2*O(n log n) + O(m log m)?

java - WebDriver - 如何让 webdriver 等到显示文本(不使用定位器)