2

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

7 Comments

This also doesnt work. The id field in mongodb is String. {'_id': "1234"}
can you put your Target class also
But mongoTemplate.findById(targetId) works fine. I need this to work with findOne and updateFirst. Which are not working at the moment.
added Target class to the question.
did u try this new Query(Criteria.where("_id").is(new ObjectId(targetId)));
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.