【问题标题】:Nested Select Query MongoDB嵌套选择查询 MongoDB
【发布时间】:2022-11-03 23:13:25
【问题描述】:

我们将 Spring Boot 与 mongo 一起使用,并有一个这样的文档:

[{
  "id": "classicId",
  "name": "classicName",
  "models": [
   {
      "id": "AnotherId",
      "name": "AnotherSomeName"
    },
     {
      "id": "RequiredId",
      "name": "SomeName"
    }
  ]
}]

数组模型中的 id 是唯一的。

输入只是模型数组的任何一个 id。所以用户只会给我们值“AnotherId”,我们需要找到文档。

我们如何使用 mongo 模板或 mongo 存储库在 java 中做到这一点?

【问题讨论】:

    标签: java spring mongodb


    【解决方案1】:

    使用MongoRepository,您可以执行以下操作:

    public Optional<YourObject> getByModelId(theVariableWithTheValue) {
        Query query = new Query().addCriteria(Criteria.where("models.id").is(theVariableWithTheValue));
        List<YourObject> result = mongoTemplate.find(query, YourObject.class);
    
        return result.isEmpty() ? Optional.empty() : Optional.of(result.get(0));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-25
      • 2018-05-08
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多