Spring Boot and Mongo - findById only works with ObjectID and not Id of String

Viewed 3725

I have a Spring Boot GraphQL service which reads from Mongo.

I've noticed that if my MongoDB document ID has ObjectID e.g. "_id": ObjectID("5e5605150") I'm able to get results from doing myRepository.findById(myId).

However if that id is just a string like "_id": "5e5605150" then findById returns nothing.

The repository looks like this:

@Repository
interface MyRepository : MongoRepository<Song, String>

And that Song looks like this:

@Document(collection = Song.COLLECTION)
data class Song(
    @Id
    val id: String,

    val title: String
) {
    companion object {
        const val COLLECTION: String = "song"
    }
}

Any ideas?

Thanks.

1 Answers

See the Spring Data MongoDB reference on mapping - the _id field is treated specially. If it's a String or BigInteger type, it will automatically be converted to/from an ObjectId. MongoDB supports plain strings for the special _id field though, so if you're inserting documents that don't go through Spring Data (or inserting documents as a raw JSON string for the MongoDB driver to insert) then MongoDB won't automatically convert strings to ObjectId - it will store them as strings.

So, if you insert the document {"_id": "5e5605150"} into your DB, the Spring Data MongoDB mapper won't be able to find it, because it will be searching by ObjectId only.

Related