Spring 查询数组中具有特定元素的记录
因此,我试图搜索具有任何给定标记(即“a”、“b”或“c”)的文档 MongoDB查询是:Spring 查询数组中具有特定元素的记录,spring,mongodb,spring-data,mongodb-query,spring-data-mongodb,Spring,Mongodb,Spring Data,Mongodb Query,Spring Data Mongodb,因此,我试图搜索具有任何给定标记(即“a”、“b”或“c”)的文档 MongoDB查询是: db.my_collection.find({ "tags" : { "$elemMatch" : { "$in" : ["a", "b", "c"] } } }) 这很好(标记是一个文档字段,它是文档的标记数组)。现在的问题是,当我尝试使用SpringData查询和Criteria对象构建此查询时 List<String> tags = Arrays.asList("a", "b", "c
db.my_collection.find({ "tags" : { "$elemMatch" : { "$in" : ["a", "b", "c"] } } })
这很好(标记是一个文档字段,它是文档的标记数组)。现在的问题是,当我尝试使用SpringData查询和Criteria对象构建此查询时
List<String> tags = Arrays.asList("a", "b", "c");
Criteria inTags = new Criteria().in(tags);
Criteria where = Criteria.where("tags").elemMatch(inTags);
Query query = new Query(where);
System.out.println(query);
这当然不会为我工作。有人知道如何使用SpringData查询/条件来实现这一点吗。我对难看的解决方案或直接使用MongoDB Java驱动程序不感兴趣——我可以做到。我想知道是否有任何方法可以正确使用SpringData类。您在这里以非标准方式使用
$elemMatch
,因为它意味着在单个数组元素中匹配多个字段。请改用如下查询:
db.my_collection.find({ "tags": "$in": ["a", "b", "c"] })
在SpringData中工作起来应该更容易。可能是一个错误的点击-对不起。
db.my_collection.find({ "tags": "$in": ["a", "b", "c"] })