【发布时间】:2020-06-19 02:33:24
【问题描述】:
因为 mongo 集合中的字段是对象到对象的变化。对象中有 4 个字段,其他有 8 个字段,所以我们如何获取所有集合数据。
【问题讨论】:
标签: java mongodb spring-boot jpa collections
因为 mongo 集合中的字段是对象到对象的变化。对象中有 4 个字段,其他有 8 个字段,所以我们如何获取所有集合数据。
【问题讨论】:
标签: java mongodb spring-boot jpa collections
不用jpa仓库也可以得到这样的文档
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.ProjectionOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.web.bind.annotation.GetMapping;
@Autowired
MongoTemplate mongoTemplate;
@GetMapping("/url")
public List<JSONObject> getList() {
ProjectionOperation project = project().andExclude("_id");
Aggregation aggregate = newAggregation(project);
AggregationResults<JSONObject> aggregationResult = mongoTemplate.aggregate(aggregate,"youCollectionName", JSONObject.class);
List<JSONObject> result = aggregationResult.getMappedResults();
return result;
}
【讨论】:
您可以使用 MongoDB Spring Data 的MongoTemplate API 方法,如下所示。
The MongoTemplate 类的findAll 方法可以使用。该方法要求指定 entityClass。如果您没有定义实体类,可以指定一个通用的org.bson.Document 类(参见下面的示例代码)。
public <T> List<T> `findAll`(Class<T> entityClass, String collectionName)
从 指定的集合。
对象是从MongoDB原生转换而来的 使用 MongoConverter 的实例表示。除非配置 否则,将使用 MappingMongoConverter 的实例。如果你的 集合不包含同质类型的集合,这 自从测试以来,操作将不是映射对象的有效方法 for class 类型是在客户端而不是在服务器上完成的。
例子:
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}}
【讨论】: