Shamnad P S
Shamnad P S

Reputation: 1173

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

Upvotes: 2

Views: 6961

Answers (2)

Shamnad P S
Shamnad P S

Reputation: 1173

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

Upvotes: 1

pvpkiran
pvpkiran

Reputation: 27048

Based on the discussions here, it looks like this is not possible to achieve. You need to change the type in database as ObjectId.

If you cannot do that, you can do

mongoTemplate.getCollection("target").findOne(<targetId>) 

But this will return a DBObject, You need to create Target instance from this

Upvotes: 1

Related Questions