Khushal Singh
Khushal Singh

Reputation: 59

Nested Select Query With Mongo Repository

We use SpringBoot with mongo and have a document like this:

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

The id in the array models is unique.

The input could be just any id in the models array. So the user will just give us the value "AnotherId" in order to find the document.

How can we do that in java using the mongo template or mongo repository?

Upvotes: 0

Views: 131

Answers (1)

ypdev19
ypdev19

Reputation: 195

With MongoRepository you could do something like:

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));
}

Upvotes: 1

Related Questions