【问题标题】:Spring Data MongoTemplate aggregation error 'input to $filter must be an array not object'Spring Data MongoTemplate 聚合错误'$filter 的输入必须是数组而不是对象'
【发布时间】:2019-03-05 11:25:52
【问题描述】:

我有一个这样的文档结构:

{
    "_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 Data 的 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");

我在控制台打印出来,查询和上面的 JSON 查询完全一样。精确的。我什至尝试过纯 Spring 数据的查询:

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

同样的错误(即使打印它会产生与上面完全相同的 JSON 查询)。保存项目的 java 对象是一个 List。我把它改成了数组Item[],还是不行。

任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    没关系,

    有人(我)错误地将一个 Item 以对象的形式而不是数组的形式放入。这搞砸了一切。刚刚删除了整条记录,一切正常。

    【讨论】:

    • 您宁愿在代码中检查 if not 数组,也不愿删除坏数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多