2

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.

1 Answer 1

1

Nevermind,

Someone (me) put in one Item by mistake in the form of an object instead of an array. That messed up everything. Just deleted that whole record and everything is normal.

Sign up to request clarification or add additional context in comments.

1 Comment

You would rather want to have an if not array check in your code than deleting bad data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.