0

所以我试图搜索具有任何给定标记(即“a”,“b”或“c”)的文档。查询在数组中具有某些元素的记录

的MongoDB的查询是:

db.my_collection.find({ "tags" : { "$elemMatch" : { "$in" : ["a", "b", "c"] } } }) 

这只是正常(标签是一个文件的字段,它是标签为文档阵列)。现在的问题是当我尝试使用SpringData Query和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); 

的这个输出是:

Query: { "tags" : { "$elemMatch" : { }}}, Fields: null, Sort: null 

这当然没有最终为我工作。有谁知道如何使用SpringData查询/标准进行这项工作。我对丑陋的变通或直接使用MongoDB Java驱动程序不感兴趣 - 我可以这样做。我想知道是否有任何方法可以使用SpringData类来完成此操作。

回答

1

您在这里以非标准方式使用$elemMatch,因为它意味着匹配单个数组元素中的多个字段。使用这样的查询来代替:

db.my_collection.find({ "tags": "$in": ["a", "b", "c"] }) 

这应该更容易在SpringData中工作。

+0

这很好!谢谢。 – Yoshiya 2013-05-03 15:16:18

+0

可能是一个流浪的点击 - 抱歉。 – Yoshiya 2014-12-10 15:14:08

相关问题