Spring Boot Mongo: "$elemMatch needs an Object"

So I’m writing a search query, but got stuck with an error.

Querying this query in Mongo Compass returns the correct results.

{$or: 
  [
    {'title': {$regex : "aard", $options: 'i'} },
    {'tags': {$elemMatch: {$regex : "aard", $options: 'i'} } },
    {'categories': {$elemMatch: {$regex : "aard", $options: 'i'} } }
  ]
}

However querying with this query in spring boot throws an error:

Query failed with error code 2 and error message ‘$elemMatch needs an Object’

@Query("{$or: [" +
  "{'title': {$regex: ?0, $options: 'i'} }, " +
  "{'tags': {$elemMatch: {$regex: ?0, $options: 'i'} } }," +
  "{'categories': {$elemMatch: {$regex: ?0, $options: 'i'} } }" +
  "] }")
List<Product> search(String input);

Smaller example code with same result:

@Query("{'categories': {$elemMatch: {$regex: ?0, $options: 'i'} } }")
List<Product> findByCategory(String category);

Mongo Document Example:

_id:1
supplier:DBRef(supplier, [object Object], undefined)
title:"Aardappels"
description:"Verse aardappels"
unitSize:"5KG"
categories:["Groente"]
tags:["Aardappels"]
price:14.99
salePrice:9.99
sale:true
amount:0
sold:0
_class: "nl.hva.ewaserver.models.Product"

Smaller Mongo Document Example:

_id:1
title:"Aardappels"
categories:["Groente"]
tags:["Aardappels"]

It’s weird, they both have the same query, but in spring boot I use parameters.
Which shouldn’t be the problem, because I’ve also tested hardcoded.

Hello @Maikel_van_Dort, welcome to the community.

This error occurs when you use $elemMatch with Single Query Condition . So, if you change your query as follows, there is no error (and works as expected).

@Query("{'categories': { $regex: ?0, $options: 'i' } }")

Note that, if you need to work with an array of objects, then it becomes necessary to use the $elemMatch operator, with multiple fields of the object. For example, with a document with the categories array field with embedded documents (or objects):

{
        "_id" : 1,
        "title" : "Aardappels",
        "categories" : [
                {
                        "a" : "a1",
                        "b" : "b1"
                },
                {
                        "a" : "y1",
                        "b" : "z1"
                }
        ]
}

Then your query need to be using $emeMatch, and this runs without any errors. E.g.:

@Query("{'categories': { $elemMatch: { a: { $regex: ?0, $options: 'i' }, b: ?1 } } }")