Make a mongo request in spring where Document contains an array

I use spring and mongo to develop an API with the following document structure:

Document-1
myId:1
array:['abc','jkl','xyz']

Document-2
myId:3
array:['qwe','mnp','xyz']

Document-3
myId:3
array:['ped','abc','xyz']

My url : localhost:8080/array=xyz
expected : document-1,document-2,document-3

My url: localhost:8080/array=xyz,abc
exoected: document-1,document-3

In short, I want all the documents to contain the entire variable arraywith a semicolon as a result .

Is there any built-in support that spring provides for this as an @Query annotation?

Or how can I understand this?

+6
source share
2 answers

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

Collection of test kits

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']
    }
])

Perform 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" ] }

@Query Spring Data MongoDB, ,

@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);
}

, . , , Custom:

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

TestRepository TestRepositoryCustom:

@Repository
public interface TestRepository extends TestRepositoryCustom, MongoRepository {

}

, TestRepositoryCustom.

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);
    }
}
+6

, Spring. , , :

{ "tags" : { "$all" : [["tag1"]] } }

@Query(value = "{ 'tags' : {$all : ?0 }}")
List<Sampling> findWithTags(String[] arrayValues);

{ "tags" : { "$all" : ["tag1"] } }
0

Source: https://habr.com/ru/post/1612408/


All Articles