我的文档结构如下:
{
"_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");
任何帮助都将不胜感激。