我们使用 Spring Data mongodb 2.1.3 版。
我们有两个集合cities
和countries
.
@Document
public class City {
private String name;
private ObjectId id;
private ObjectId countryId;
}
@Document
public class Country {
private String name;
private ObjectId id;
}
我们有扩展的数据库存储库org.springframework.data.mongodb.repository.MongoRepository
。
现在我们要创建返回聚合数据的 REST API 端点CityCountryDto
。出于这个原因,我们要制作只读视图cityCountry
https://docs.mongodb.com/manual/reference/method/db.createView/
db.createView (
"cityCountry",
"city",
[
{ $lookup: { from: "country", localField: "countryId", foreignField: "id", as: "country_docs" } },
{ $project: { "country_docs._id": 0} }
]
)
我们尝试了
@Document
CityCountry extends City {
private Country country;
}
请注意,为了使其工作,我们必须在数据库中运行应用程序之前创建视图,或者我们必须使用数据更改日志工具(如 Flyway 或 liquibase 或 mongobee)。为了使事情变得更容易,在我们启动应用程序之前,请考虑数据库中存在的视图。
我的问题,是否有开箱即用的 Spring 数据支持视图?有没有更好的方法来实现这一目标?