Mongo聚合查询到等效的Spring Mongo数据

时间:2020-09-24 12:13:25

标签: spring mongodb spring-data-mongodb

我目前无法将以下查询转换为Spring mongo数据代码。

db.getCollection('collectionName')。aggregate([{“ $ match”:{
“ _id”:{“ $ in”:[11869099,11111]}}},{$ project:{ behavior_traces:{$ filter:{ 输入:“ $ behavior_traces”, 如:'behavior_trace', cond:{$ eq:['$$ behavior_trace.event_type',{event_type:“ candidateImage”}]}} }}
}},{$ project:{ behavior_traces:{$ arrayElemAt:[“ $ behavior_traces”,-1]} }}])

我的第一个MatchOperation和第二个Projection的工作方式如下,但是无法添加第三个投影来获取每个文档数组的最后一个元素:

private MatchOperation getMatchOperation(List<Integer> candidateUserIds) {
    Criteria inCriteria = Criteria.where("_id").in(candidateUserIds);
    return match(inCriteria);
}

private ProjectionOperation getFilterProjectOperation() {
    return project().and(filter("behavior_traces")
            .as("behavior_trace")
            .by(valueOf(
                    "behavior_trace.event_type.event_type")
                    .equalToValue(
                            "candidateImage")))
            .as("behavior_traces");
}

1 个答案:

答案 0 :(得分:1)

这是您的代码:

import org.springframework.data.mongodb.core.aggregation.ArrayOperators.ArrayElemAt; 

private ProjectionOperation getArrayProjectOperation() {
            return project("")
                .and(ArrayElemAt.arrayOf("behavior_traces").elementAt(-1).as("behavior_traces"));
        }

OR

private ProjectionOperation getArrayProjectOperation() {
            return project("")
                    .and("behavior_traces").arrayElementAt(-1).as("behavior_traces");
}