简体   繁体   中英

Mongo Aggregation query to equivalent Spring Mongo Data

I am currently stuck with converting below query to spring mongo data code.

db.getCollection('collectionName').aggregate([ { "$match": {
"_id": { "$in": [11869099,11111] } }}, { $project: { behavior_traces: {$filter: { input: '$behavior_traces', as: 'behavior_trace', cond: {$eq: ['$$behavior_trace.event_type',{event_type:"candidateImage"}]} }}
}}, { $project: { behavior_traces:{ $arrayElemAt: [ "$behavior_traces", -1 ] } }} ])

I have first MatchOperation and second Projection working as below, but could not add third projection to fetch last element of array of each document:

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");
}

Here is your code:

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM