Make mongo query in spring where Document contain array Make mongo query in spring where Document contain array mongodb mongodb

Make mongo query in spring where Document contain array


You essentially want to use the $all operator to get the desired results. In the mongo shell, the following operation will bring the documents:

Populate test collection

db.test.insert([    {        _id: 1,        myId: 1,        array: ['abc','jkl','xyz']    },    {        _id: 2,        myId: 3,        array: ['qwe','mnp','xyz']    },    {        _id: 3,        myId: 3,        array:['ped','abc','xyz']    }])

Run operations

> db.test.find({"array": { "$all": ["xyz"] }}){ "_id" : 1, "myId" : 1, "array" : [ "abc", "jkl", "xyz" ] }{ "_id" : 2, "myId" : 3, "array" : [ "qwe", "mnp", "xyz" ] }{ "_id" : 3, "myId" : 3, "array" : [ "ped", "abc", "xyz" ] }> db.test.find({"array": { "$all": ["abc", "xyz"] }}){ "_id" : 1, "myId" : 1, "array" : [ "abc", "jkl", "xyz" ] }{ "_id" : 3, "myId" : 3, "array" : [ "ped", "abc", "xyz" ] }

As with the @Query annotation in Spring Data MongoDB, I haven't tested this but you may want to try the following custom query implementation example

@Document(collection="test")class Test {    int myId;    String[] array;}public interface TestRepository extends MongoRepository<Test, Integer> {    @Query(value = "{ 'array' : {$all : [?0] }}")    public List<Test> findAnyOfTheseValues(String[] arrayValues);}

If the above doesn't work for you, you may want to create a custom interface and your implementation class to execute the custom query. For example, create an interface with a name that appends Custom:

public interface TestRepositoryCustom {    public List<Test> findAnyOfTheseValues(String[] arrayValues); }

Modify the TestRepository and add the TestRepositoryCustom interface to be extended:

@Repositorypublic interface TestRepository extends TestRepositoryCustom, MongoRepository {}

Create your implementation class to implement the methods defined in TestRepositoryCustom interface.

public class TestRepositoryImpl implements TestRepositoryCustom {    @Autowired    MongoTemplate mongoTemplate;    @Override    public List<Test> findAnyOfTheseValues(String[] arrayValues) {        return mongoTemplate.find(            Query.query(Criteria.where("array").all(arrayValues)), Test.class);    }}