I have a collection ref
consisting of
{
"_id": "refId"
"ref": "itemId"
}
and a collection item
{
"_id": "itemId"
"field1": ...
"array": [
{
"field2": "a"
},
{
"field2": "b"
}
]
}
Here i need to 'join' a.k.a perform a lookup
on ref
to item
, and project the fields field1
and the last item of array
as arrayItem
into the top level of the return document, to return
{
"_id": "itemId",
"field1": ...
"arrayItem: "b"
}
Using the mongo shell, this works perfectly using the following statement:
db.ref.aggregate([
{ "$lookup": {
"from": "item",
"localField": "ref",
"foreignField": "_id",
"as": "item"
}},
{ "$unwind": "$item" },
{ "$project": {
"_id": "$item._id",
"field1": "$item.field1",
"arrayItem": { $slice: [ "$item.array", -1, 1 ]}
}},
{ "$unwind": "$arrayItem" }
])
Now, i have to make this happen in Java with Spring and Spring-MongoDB, which i have tried using this Aggregation:
Aggregation.newAggregation(
new LookupAggreationOperation("item", "ref", "_id", "item"),
Aggregation.unwind("item"),
Aggregation.project(Fields.from(
Fields.field("_id", "$item._id"),
Fields.field("field1", "$item.field1"),
Fields.field("array", "$item.array"))),
Aggregation.project("_id", "field1", "array")
.and("$array").project("slice", -1, 1).as("$arrayItem"),
Aggregation.unwind("$array"));
As lookup is only available in Spring-Mongo 1.9.2, I had to rebuild it myself like that:
public class LookupAggregationOperation implements AggregationOperation {
private 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);
}
}
The problem is that the slice command is not yet implemented as method in Aggregation (and isn't in 1.9.2), hence i need to call project("slice", -1, 1).as("$arrayItem")
as suggested in DATAMONGO-1457. The slicing is simply not executed, arrayItem
is null in the result.
I'm using Spring 1.3.5 with Spring MongoDB 1.8.4 and MongoDB 3.2.8.