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?

Tristan
  • 11
  • 1
  • 3

3 Answers3

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;
}
lczapski
  • 4,026
  • 3
  • 16
  • 32
guodong508
  • 21
  • 2
1

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)
Matej Marconak
  • 1,365
  • 3
  • 20
  • 25
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

Fernix
  • 361
  • 3
  • 10