spring-data-mongodb: how to find document by passing random attribute and its value

753 views Asked by At

I have below document in my mongodb.

{
    "_id" : "840e922e-05e0-4e4d-b574-303a72425bdd",
    "_class" : "com.document.domain.Doc",
    "type" : "User",
    "name" : "steven",
    "index" : 0,
    "data" : "This is sample user",
    "properties" : {
        "displayName" : "steven",
        "lastName" : "smith"
    },
    "tags" : [ 
        "tag1", 
        "tag2"
    ],
    "categories" : [ 
        "category1", 
        "category2"
    ]
}

Now I want to retrieve document by passing any random attribute from above json.

Example: If I pass "type" as a key and "User" as value
         If I pass "name" as a key and "steven" as value

Like this key can be any random attribute from JSON and value will be its associates value, then it should return me that document.

I am trying below Query:

@Query("{'property':?0,'property':?1}")
List<Doc> findByKeyAndValue(String key, String value);

But no luck.

Thanks in advance.

1

There are 1 answers

0
chridam On BEST ANSWER

Try changing the placeholders that let you substitute the key and value from the method arguments into the JSON query string, where ?0 is the placeholder for the key and ?1 for the value. For example,

@Query("{?0:?1}")
List<Doc> findByKeyAndValue(String key, String value);