【发布时间】:2020-09-09 19:05:50
【问题描述】:
我正在使用 Spring (boot) data 2.2.7 和 mongodb 4.0。 我已经设置了 3 个我试图通过聚合查找操作加入的集合。
- 目录
- 库存
- 操作
目录
{
"_id" : ObjectId("5ec7856eb9eb171b72f721af"),
"model" : "HX711",
"type" : "DIGITAL",
....
}
映射者
@Document(collection = "catalog")
public class Product implements Serializable {
@Id
private String _id;
@TextIndexed
private String model;
....
库存
{
"_id" : ObjectId("5ec78573b9eb171b72f721ba"),
"serialNumber" : "7af646bb-a5a8-4b86-b56b-07c12a625265",
"bareCode" : "72193.67751691974",
"productId" : "5ec7856eb9eb171b72f721af",
......
}
映射者
@Document(collection = "stock")
public class Component implements Serializable {
@Id
private String _id;
private String productId;
....
productId 字段指的是目录集合中的 _id
运营
{
"_id" : ObjectId("5ec78671b9eb171b72f721d3"),
"componentId" : ""5ec78573b9eb171b72f721ba",
.....
}
映射者
public class Node implements Serializable {
@Id
private String _id;
private String componentId;
....
componentId 字段是指股票集合中的 _id 字段
我想查询 operations 或 stock 集合以检索按 Product.model 字段排序的相应 Node 或 Component 对象列表(在 catalog强>集合。)
虽然目标是用 Java 编写代码,但我尝试先在 Mongo shell 中发出请求,但在尝试加入时我什至无法正常工作(查找)带有 ObjectId 的字符串:Node.componentId -> Component._id Component.productId -> Product._id
对于关系 Component(stock) -> Product(Catalog) 我试过了
LookupOperation lookupOperation = LookupOperation.newLookup()
.from("catalog")
.localField("productId")
.foreignField("_id")
.as("product");
TypedAggregation<Component> agg =
Aggregation.newAggregation(
Component.class,
lookupOperation
);
AggregationResults<Component> results = mongoTemplate.aggregate(agg, "stock", Component.class);
return results.getMappedResults();
但它会返回没有产品信息的整个组件记录。
[{"_id":"5ec78573b9eb171b72f721b0","uuId":"da8800d0-b0af-4886-80d1-c384596d2261","serialNumber":"706d93ef-abf5-4f08-9cbd-e7be0af1681c","bareCode":"90168.94737714577","productId":"5ec7856eb9eb171b72f721a9","created":"2020-05-22T07:55:31.66","updated":null}, .....]
感谢您的帮助。
注意: 除了@Valijon 回答能够按预期获得结果之外,返回的对象必须包含“产品”属性,否则不会返回任何内容(例如使用 JSON REST 服务)
public class ComponentExpanded implements Serializable {
private String product;
....
与
AggregationResults<ComponentExpanded> results =
mongoTemplate.aggregate(agg,mongoTemplate.getCollectionName(Component.class), ComponentExpanded.class);
【问题讨论】:
标签: mongodb spring-boot aggregation-framework lookup-tables