Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 936
userMod2 Avatar asked Oct 31 '25 04:10

userMod2


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.

like image 111
Logan Pickup Avatar answered Nov 01 '25 19:11

Logan Pickup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!