您基本上想要使用$all
运算符来获得所需的结果。在蒙戈外壳,下面的操作将带来的文件:
填充测试集
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']
}
])
运行操作
> 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" ] }
与春季数据的MongoDB的@Query
注释,我没有测试过这一点,但你可能要尝试以下自定义查询实现例如
@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);
}
如果上述方法不为你工作,你可能想创建一个自定义接口和实现类来执行自定义查询。例如,创建一个接口与附加自定义一个名字:
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);
}
}
我已经测试了@Query,但是它并不按照它的方式工作。我得到localhost的结果:8080 /数组= ABC,XYZ。它是只给有“数组”的文件:“ABC”,“XYZ”]只。即使订单也很重要。而不是给包含数组的文件:[“abc”,“xyz”,“ped”]。测试第二个解决方案 –
非常感谢,但是大小写不敏感,可能吗? +1 – Jaiwo99