$and query in mongo db with @Query annotation not working in spring data jpa

75 Views Asked by At

I am developing one application based on spring boot with jpa repository in it for the mongo database. I am using below annotation with query

@Query("{'$and':[ {'characteristics.name':?0}, {'characteristics.value':?1} ]}")

@Repository
public interface ResourceRepository extends MongoRepository<Resource, String> {

    @Query("{'$and':[ {'characteristics.name':?0}, {'characteristics.value':?1} ]}")
    Optional<Resource> findResourceByMacAddressWithValue(String macAddress, String value);

}

my Resource object looks like this :

@Document(collection = "resource")
@Data
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Resource extends BaseAuditer implements Serializable {

    @Id
    private String id;
    private String type;
    private List<ResourceCharacteristics> characteristics;
}

and ResourceCharacteristics looks like this :

@Data
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ResourceCharacteristics {

    private String name;
    private String value;

}

My goal is to use find resource if that resource has some particular name and with some value...so I am using above and query but it is working like or query when I tested, I wanted to make it work like and query only.

anybody can help me in this what's wrong that I am doing in this query annotation.

1

There are 1 best solutions below

1
John Williams On

Try removing the $and

@Query("{characteristics.name: ?0, characteristics.value: ?1}")