javamongodbspring-bootmongo-javamongo-java-driver

Java mongoTemplate findOne query not returning results when id is String


I have the below query to find MongoDB document using mongoTemplate. This is not returning any results when I search my Target using Id.

Query query = new Query(Criteria.where("id").is(String.valueOf(targetId)));
mongoTemplate.findOne(query, Target.class));

But the query works when I use any fields other than Id. Could someone help me to work this using Id.

Target class

@Data
@Document
public class Target {
    @Id
    private String id;
    /**
     * Name of the target
     */
    private String name;
}

DB document.

{
    "_id" : "5290d748e4",
    "name" : "Test Target"
}

Query By name is working fine.

Query query = new Query(Criteria.where("name").is("Test Target"));
mongoTemplate.findOne(query, Target.class));

Solution

  • I was able to get the required functionality by using MongoCollection.

    MongoDatabase mongoDatabase = mongoTemplate.getDb();
    MongoCollection<Document> targetCollection
                        = mongoDatabase.getCollection(mongoTemplate.getCollectionName(Target.class));
    Document query = new Document();
    query.put("_id", parkTargetId);
    query.put("spots._id", parkingSpotId);
    
    targetCollection.find(query);