Reputation: 8386
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:
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?
Upvotes: 5
Views: 7618
Reputation: 103435
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);
Upvotes: 6