【问题标题】:Search a list of text in an embedded array using Spring data Mongo使用 Spring 数据 Mongo 在嵌入式数组中搜索文本列表
【发布时间】:2019-07-07 14:15:06
【问题描述】:

我必须创建一个服务,它接受文本列表并在 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"}]}]

搜索上面的文字应该会返回这三部电影。它需要我创建如下查询:

db.movies.find({cast.name: {$in: [/Tom/, /Keanu/, /Arnold/]}})

这是因为根据official doc,我们不能将$regex$in 一起使用。但是我无法找到将其转换为 Spring Data Mongo 查询的方法。

这个Stackoverflow 线程解释了如何使用正则表达式在嵌入式数组中搜索单个文本,但我找不到任何关于使用 Spring 数据 Mongo 从嵌入式文档中的给定列表中搜索的任何内容。任何帮助将不胜感激。

【问题讨论】:

    标签: java regex mongodb spring-data-mongodb


    【解决方案1】:

    您应该能够使用$elemMatch 和正则表达式标准来执行此操作。 $elemMatch equivalent in spring data mongodb在spring数据中有很好的讨论$elemMatch。比如:

    Criteria.where("cast").elemMatch(Criteria.where("name").regex("Tom|Keanu|Arnold"));
    

    【讨论】:

    • 成功了!谢谢,将此标记为正确答案。
    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-29
    • 2018-08-15
    • 2011-12-14
    • 1970-01-01
    相关资源
    最近更新 更多