因为 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/