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