【问题标题】:How to query nested objects from MongoDB using Spring Boot (REST) and TextQuery?如何使用 Spring Boot (REST) 和 TextQuery 从 MongoDB 查询嵌套对象?
【发布时间】:2020-05-18 14:51:36
【问题描述】:

我正在编写 RESTful API 以使用 TextQuery 按条件搜索名为“global”的 MongoDB 集合。我的问题是在进行查询时我无法访问嵌套对象字段。

例如这有效:

GET localhost:8080/search?criteria=name:'name'

这不是:

GET localhost:8080/search?criteria=other.othername:'Other Name'

我有 MongoDB json 结构(从 JSON 导入到“全局”集合中作为整个嵌套对象)

[{
   "name": "Name",
   "desc": "Desc",
   "other" {
     "othername": "Other Name",

    }
 },
 {
   "name": "Name",
   "desc": "Desc",
   "other" {
     "othername": "Other Name",

    }
 }
]

和类(带有 getter 和 setter 等):

@Document(collection="global")
public class Global{
  @TextIndexed
  String name;
  @TextIndexed
  String desc;
  Other other;
  ...
}


public class Other{
  String othername;
  ...
}

我的控制器有方法

@GetMapping("/search")
 public Iterable<Global> getByCriteria(@RequestParam("criteria") String criteria) {
...
}

我正在尝试使用

编写文本搜索
public Iterable<Global> findByCriteria(String criteria) {
        TextCriteria criteria = TextCriteria.forDefaultLanguage().matching(criteria);
        TextQuery query = TextQuery.queryText(criteria);
        return mongoTemplate.find(query, Global.class);
    }

【问题讨论】:

    标签: spring mongodb rest spring-boot


    【解决方案1】:

    您需要将@TextIndexed 添加到您的other 字段中。

    public class Global{
      @TextIndexed
      String name;
      @TextIndexed
      String desc;
      @TextIndexed
      Other other;
      ...
    }
    

    注意:所有嵌套对象字段都是可搜索的

    或者您可以为每个嵌套对象字段添加@TextIndexed

    public class Other {
      @TextIndexed
      String othername;
      ...
    }
    

    【讨论】:

    • 感谢您的回答。我认为这行得通。你能建议我如何在标准中传递更多参数吗?类似于:GET localhost:8080/search?criteria=name:'name',other.othername:'Other Name'
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 2021-12-15
    • 2012-07-23
    • 2023-03-12
    相关资源
    最近更新 更多