Spring mongodb:使用查找,投影和切片进行聚合

时间:2016-08-24 08:47:21

标签: java spring mongodb aggregation-framework mongodb-aggregation

我有一个由

组成的集合ref
{
  "_id": "refId"
  "ref": "itemId"
}

和集合item

{
  "_id": "itemId"
  "field1": ...
  "array": [
    {
      "field2": "a"
    }, 
    {
      "field2": "b"
    }
  ]
}

在这里,我需要'加入',然后在lookuprefitem执行field1,并投放字段arrayarrayItem的最后一项将{ "_id": "itemId", "field1": ... "arrayItem: "b" } 作为返回文档的顶级,返回

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

使用mongo shell,使用以下语句完美地工作:

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

现在,我必须使用Spring和Spring-MongoDB在Java中实现这一点,我尝试使用此聚合:

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

由于查找只在Spring-Mongo 1.9.2中可用,我不得不自己重建它:

project("slice", -1, 1).as("$arrayItem")

问题是slice命令尚未作为Aggregation中的方法实现(并且不在1.9.2中),因此我需要按照DATAMONGO-1457中的建议调用arrayItem。切片根本不执行,结果中exit()为空。

我正在使用Spring 1.3.5和Spring MongoDB 1.8.4以及MongoDB 3.2.8。

0 个答案:

没有答案