使用 Spring 数据 Mongo 在嵌入数组中搜索文本列表
Search a list of text in an embedded array using Spring data Mongo
我必须创建一项服务,该服务获取文本列表并在 MongoDB 文档的嵌入式数组中搜索匹配项。例如,
我必须搜索此文本列表:
["Tom", "Keanu", "Arnold"]
在以下集合中:
[{id: "123", title: "Movie 1", cast: [{id: 1, name: "Tom Hanks"}, {id: 2, name: "Actor 2"}]},
{id: "123", title: "Movie 1", cast: [{id: 1, name: "Keanu Reeves"}, {id: 2, name: "Actor 2"}]}
{id: "123", title: "Movie 1", cast: [{id: 1, name: "Arnold Schwarzenegger"}, {id: 2, name: "Actor 2"}]}]
搜索上面的文字应该return这三部电影。它要求我创建如下查询:
db.movies.find({cast.name: {$in: [/Tom/, /Keanu/, /Arnold/]}})
这是因为根据 official doc,我们不能将 $regex
与 $in
一起使用。但是我找不到将其转换为 Spring 数据 Mongo 查询的方法。
这个 线程解释了如何使用正则表达式在嵌入式数组中搜索单个文本,但我找不到任何有关使用 Spring 数据从嵌入式文档中的给定列表进行搜索的信息Mongo。任何帮助将不胜感激。
您应该能够使用 $elemMatch
和正则表达式条件来执行此操作。 $elemMatch equivalent in spring data mongodb 在 spring 数据中对 $elemMatch
进行了很好的讨论。类似于:
Criteria.where("cast").elemMatch(Criteria.where("name").regex("Tom|Keanu|Arnold"));
我必须创建一项服务,该服务获取文本列表并在 MongoDB 文档的嵌入式数组中搜索匹配项。例如, 我必须搜索此文本列表:
["Tom", "Keanu", "Arnold"]
在以下集合中:
[{id: "123", title: "Movie 1", cast: [{id: 1, name: "Tom Hanks"}, {id: 2, name: "Actor 2"}]},
{id: "123", title: "Movie 1", cast: [{id: 1, name: "Keanu Reeves"}, {id: 2, name: "Actor 2"}]}
{id: "123", title: "Movie 1", cast: [{id: 1, name: "Arnold Schwarzenegger"}, {id: 2, name: "Actor 2"}]}]
搜索上面的文字应该return这三部电影。它要求我创建如下查询:
db.movies.find({cast.name: {$in: [/Tom/, /Keanu/, /Arnold/]}})
这是因为根据 official doc,我们不能将 $regex
与 $in
一起使用。但是我找不到将其转换为 Spring 数据 Mongo 查询的方法。
这个
您应该能够使用 $elemMatch
和正则表达式条件来执行此操作。 $elemMatch equivalent in spring data mongodb 在 spring 数据中对 $elemMatch
进行了很好的讨论。类似于:
Criteria.where("cast").elemMatch(Criteria.where("name").regex("Tom|Keanu|Arnold"));