I have a document structure like this:
{
"_id" : ObjectId("...."),
"oneMoreId" : "....",
"items" : [
{
"itemId" : "...",
"type" : "Food",
}
]
}
When I run JSON query in mongodb:
db.inventory.aggregate([
{$match: { $and: [{"oneMoreId":"..."},{"items.type": "Food"}]}},
{"$project": {
"oneMoreId": 1,
"items": {
"$filter": {
"input": "$items",
"as": "item",
"cond": {
"$eq": ["$$item.type", "Food"]
}
}
}
}}
])
It works perfectly fine.
But when I use Spring Data's MongoTemplate to run aggregation, It throws me
input to $filter must be an array not object
This is my aggregation query (just the projection part):
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");
I print it out in console and query is exactly the same as JSON query above. Exact. I have even tried pure Spring data's query:
ProjectionOperation projection = project("oneMoreId")
.and(filter("items")
.as("item")
.by(valueOf("item.type")
.equalToValue("Food"))).as("items");
Again, same error (even though printing it results in the same exact JSON query above). The java object that holds items was a List. I changed it to just array Item [], and it still didn't work.
Any help would be greatly appreciated.