1

I have a collection, with documents having a field named _id of type String, not generated manually.

I have been trying to get a document using its id.

    val criteria = Criteria.where("_id").`is`("a2z3e44R")
    val document = mongoTemplate.findOne(Query.query(criteria), MyDocument::class.java) // returns null

    val criteria = Criteria.where("_id").`is`(ObjectId("a2z3e44R"))
    val document = mongoTemplate.findOne(Query.query(criteria), MyDocument::class.java) // returns null

    val document = mongoTemplate.findById("a2z3e44R", MyDocument::class.java) // returns null

    mongoTemplate.findAll(MyDocument::class.java).first { myDocument ->
        myDocument._id == "a2z3e44R"
    } // OK...

MyDocument is

data class MyDocument(val _id: String, val name: String)

Trying to find a document by another field works.

An idea of what I could be missing or a workaround?

1
  • 1
    Can you please post your JSON document the way you get it through mongo.exe or Robo3T? Commented Oct 9, 2018 at 19:18

3 Answers 3

2

Try mark _id with annotation @Id. The @Id annotation is used to specify the identifier for Spring.

data class MyDocument(@Id val _id: String, val name: String)
Sign up to request clarification or add additional context in comments.

3 Comments

I implemented your suggestion using import org.springframework.data.annotation.Id but the result remains the same.
How do you persist new data?
It is another program taking care of adding data. I am only reading them.
2

You should indicate the type of the id like this

public class Article {

    @MongoId(value = FieldType.OBJECT_ID)
    private String id;

    private String title;

    private String desc;
}

1 Comment

That is a winner answer
0

Ypu could define in your repository:

public interface MyDocumentRepository extends MongoRepository<MyDocument, String> {
  Pets findBy_id(ObjectId _id);
}

and use it :

myDocumentRepository.findBy_id("a2z3e44R");

for more info see

or

ObjectId objID = new ObjectId("a2z3e44R");
      query.addCriteria(Criteria.where("_id").lt(objID));

like this other answer link

1 Comment

This solution is not working either. This was my initial code.

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.