Query an array with regular expression in mongo repository

331 Views Asked by At

The following query is not working for mongo repository -

@Query(value = "{ 'items' : {$elemMatch : {'attributes' : {$all : [/^?0/i]}}}}")
List<MenuEntity> findMenuByItemAttribute(String attrName);

The problem seems to be where I am passing ?0 in the annotation. Do I need to pass quotes somewhere?

db.menus.find({ 'items' : {$elemMatch : {'attributes' : {$all : [/^sav/i]}}}})

The above query returns the result in mongo shell

Document Structure -

db.menus.findOne()
{
    "_id" : ObjectId("5cf25412326c3f4f26df039b"),
    "restaurantId" : "301728",
    "items" : [
            {
                    "itemId" : "CEBM4H41JR",
                    "name" : "Crun Chicken",
                    "imageUrl" : "",
                    "price" : 572,
                    "attributes" : [
                            "Tasty",
                            "Spicy"
                    ]
            },
            {
                    "itemId" : "53Q0XS3HPR",
                    "name" : "Devils Chicken",
                    "imageUrl" : "",
                    "price" : 595,
                    "attributes" : [
                            "Gravy",
                            "Salty"
                    ]
            }
}
1

There are 1 best solutions below

0
On

It is not necessary to write the mongo query by yourself. You can extend MongoRepository and use a derived query just defining your method in the interface like:

List<MenuEntity> findByItemsAttributes(String attribute);