Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregation query with lookup in Spring

I'm using the Spring framework to perform an aggregation on my mongodb. However, the lookup keeps failing and I can't understand why. Here's the query:

Aggregation aggregation = newAggregation(
    match(Criteria.where("idOfUser").is(loggedInAccount.getId())),
    group("imgID"),
    new CustomAggregationOperation(
        new BasicDBObject("$lookup",
        new BasicDBObject("from","img")
            .append("localField","_id")
            .append("foreignField","_id")
            .append("as","uniqueImgs")
        )
    ),
    limit(pageable.getPageSize()),
    skip(pageable.getPageSize()*pageable.getPageNumber())
);

AggregationResults aggregationResults = mongo.aggregate(aggregation, "comment", String.class); //Using String at the moment just to see the output clearly.

CustomAggregationOperation is as follows:

public class CustomAggregationOperation implements AggregationOperation {
    private DBObject operation;

    public CustomAggregationOperation (DBObject operation) {
        this.operation = operation;
    }

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

The Spring MongoDB version of lookup isn't recognised which is why I'm using this CustomAggregationOperation. AFAIK it shouldn't affect it.

Ideally what I want to happen is:

  1. Get all the comments of the user.
  2. Make sure that the imgID is distinct for the comments (so there are only the id's of the imgs that have been commented on)
  3. Get the actual img objects related to these ids.
  4. Paginate the returned imgs.

At the moment, step 3 doesn't work, and I think 4 wouldn't work either since limit and skip won't be applied to the objects in "uniqueImgs". What is returned is:

[{ "_id" : "570e2f5cb1b9125510a443f5" , "uniqueImgs" : [ ]}]

How can I fix this?

EDIT the imgID stored isn't an ObjectID whereas the _id in the img collection is. Would that have any effect?

like image 256
Tometoyou Avatar asked Apr 15 '16 17:04

Tometoyou


1 Answers

The current release (at the time of writing 1.9.5) has support for the $lookup operator and can be implemented as (untested):

LookupOperation lookupOperation = LookupOperation.newLookup()
    .from("img")
    .localField("_id")
    .foreignField("_id")
    .as("uniqueImgs");

Aggregation agg = newAggregation(
    match(Criteria.where("idOfUser").is(loggedInAccount.getId())),
    group("imgID"),
    lookupOperation,
    limit(pageable.getPageSize()),
    skip(pageable.getPageSize()*pageable.getPageNumber())
);

AggregationResults aggregationResults = mongo.aggregate(agg, "comment", String.clas);
like image 190
chridam Avatar answered Sep 24 '22 02:09

chridam