从String到ObjectId的Spring数据MongoDb聚合查找

时间:2020-05-22 20:40:46

标签: mongodb spring-boot aggregation-framework lookup-tables

我在mongodb 4.0中使用Spring(引导)数据2.2.7。 我已经设置了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 一个

我想查询操作库存集合,以检索由Product.model字段排序的相应节点或组件对象列表(在目录集合。)

虽然目标是使用Java编写代码,但是我尝试先在 Mongo shell 中提出请求,但是在尝试加入(查找)时我什至无法使它正常工作具有ObjectId的字符串:Node.componentId-> Component._id Component.productId-> Product._id

对于关系Component(股票)->我尝试过的Product(目录)

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答案,以便能够按预期方式获得结果,返回的对象还必须包含“ product”属性,否则将不返回任何内容(例如,使用JSON REST服务)

public class ComponentExpanded implements Serializable {

    private String product;
....

AggregationResults<ComponentExpanded> results =
        mongoTemplate.aggregate(agg,mongoTemplate.getCollectionName(Component.class), ComponentExpanded.class);

1 个答案:

答案 0 :(得分:1)

如您所见,问题出在productId_id之间类型不匹配。

要加入这些数据,我们需要执行uncorrelated sub-queries,并且并非每个“新”功能都会使其立即进入抽象层,例如spring-mongo

尝试一下:

Aggregation agg = Aggregation.newAggregation(l -> new Document("$lookup",
    new Document("from", mongoTemplate.getCollectionName(Product.class))
        .append("let", new Document("productId", new Document("$toObjectId", "$productId")))
        .append("pipeline",
                Arrays.asList(new Document("$match",
                        new Document("$expr",
                                new Document("$eq", Arrays.asList("$_id", "$$productId"))))))
        .append("as", "product")),
    Aggregation.unwind("product", Boolean.TRUE));

AggregationResults<Component> results = mongoTemplate.aggregate(agg, 
    mongoTemplate.getCollectionName(Component.class), Component.class);
return results.getMappedResults();

MongoPlayground在此处检查外壳查询的外观。

注意:对于Java v1.7,您需要像下面这样实现AggregationOperation

AggregationOperation l = new AggregationOperation() {

    @Override
    public Document toDocument(AggregationOperationContext context) {
        return new Document(...); // put here $lookup stage
    }

};