4

我有一个集合ref,包括

{
  "_id": "refId"
  "ref": "itemId"
}

和一个集合item

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

在这里,我需要“加入”,也就是执行一个lookup到,并将字段和as的最后一项投影ref到返回文档的顶层,以返回itemfield1arrayarrayItem

{
  "_id": "itemId",
  "field1": ...
  "arrayItem: "b"
}

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

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

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

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-Mongo 1.9.2 中可用,我不得不自己重建它:

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

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

我将 Spring 1.3.5 与 Spring MongoDB 1.8.4 和 MongoDB 3.2.8 一起使用。

4

0 回答 0