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 类是否有任何方法可以做到这一点。

4

1 回答 1

2

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

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

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

于 2013-05-03T13:05:12.797 回答