代码之家  ›  专栏  ›  技术社区  ›  Faraz

Spring Data MongoTemplate聚合错误'input to$filter must be a array not object'

  •  0
  • Faraz  · 技术社区  · 7 年前

    我的文档结构如下:

    {
        "_id" : ObjectId("...."),
        "oneMoreId" : "....",
        "items" : [
                {
                        "itemId" : "...",
                        "type" : "Food",
                }
        ]        
    }
    

    在mongodb中运行JSON查询时:

    db.inventory.aggregate([
    {$match: { $and: [{"oneMoreId":"..."},{"items.type": "Food"}]}},
    {"$project": {
    "oneMoreId": 1,
    "items": {
        "$filter": {
            "input": "$items",
            "as": "item",
            "cond": {
                "$eq": ["$$item.type", "Food"]
            }
        }
    }
    }}
    ])
    

    但是,当我使用Spring数据的MongoTemplate运行聚合时,它会让我

    $filter的输入必须是数组而不是对象

    ProjectionOperation projection = project("oneMoreId").and(new AggregationExpression() {
    
    @Override
    public Document toDocument(AggregationOperationContext context) {
        return new Document("$filter", new Document(
                      "input", "$items")
                      .append("as","item")
                      .append("cond", new Document("$eq", Arrays.asList("$$item.type","Food")))
                  );
    }
    }).as("items");
    

    ProjectionOperation projection = project("oneMoreId")
        .and(filter("items")
                .as("item")
                .by(valueOf("item.type")
                        .equalToValue("Food"))).as("items");
    

    任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Faraz    7 年前

    没有关系,