首页 > 解决方案 > 如何使用 Spring Data MongoDB 1.8.2 进行“加入”查找?

问题描述

我需要在两个不同的表之间进行“连接”,我的查询是这样的:

db.Summary.aggregate([
    {
        $lookup: {
           from: "OriginFilter",
           localField: "origin",
           foreignField: "code",
           as: "originObject"
        }
    },
    {
        $project: {
            "hub": 1,
            "moment": 1,
            "origin": { $arrayElemAt: [ "$originObject.displayName", 0 ] },
            "_id": 0
        }
    }
]);

并且工作完美,但我不知道如何在代码中使用 java 和 spring 来做到这一点。

我有 LookupAggregationOperation 类:

public class LookupAggregationOperation implements AggregationOperation {
    private final DBObject operation;

    public LookupAggregationOperation(String from, String localField,
                                      String foreignField, String as) {
        
        this.operation = new BasicDBObject("$lookup",
                new BasicDBObject("from", from)
                        .append("localField", localField)
                        .append("foreignField", foreignField)
                        .append("as", as));
    }

    @Override
    public DBObject toDBObject(AggregationOperationContext context) {
        return context.getMappedObject(operation);
    }

我以这种方式使用它:

LookupAggregationOperation getOriginDisplayName = new LookupAggregationOperation("OriginFilter","origin","code","originObject");

然后,我有一个 groupOperation:

GroupOperation groupByDay = group("moment.year", "moment.month", "moment.day", "moment.hour", "countType", "origin", "originObject")
                .sum("$count").as("count");

最后我有一个 ProjectOperation:

ProjectionOperation renameFields = project("count", "countType")
                .and("_id.originObject.displayName").as("originDisplayName").and("_id.year").as("moment.year")
                .and("_id.month").as("moment.month")
                .and("_id.day").as("moment.day")
                .and("_id.hour").as("moment.hour");

and("_id.originObject.displayName").as("originDisplayName")不工作。如何进行上述查询?

标签: javaspringmongodbaggregation-frameworkspring-data-mongodb

解决方案


推荐阅读