【发布时间】: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