spring-data-mongodb
spring-data-mongodb copied to clipboard
mongoTemplate sends strings as objectIds
mongoTemplate seems to automatically convert strings to ObjectIds, which can lead to undesired behavior
I'm using mongo 6.x and spring-data-mongo 4.0.8
See the following test and its log output:
@Test
void mongoObjectIdConversion() {
ObjectId objectId = ObjectId.get();
mongoTemplate.updateFirst(Query.query(where("_id").is(objectId)), new Update().set("foo", "bar"), "testcol");
mongoTemplate.updateFirst(Query.query(where("_id").is(objectId.toHexString())), new Update().set("foo", "bar"), "testcol");
mongoTemplate.updateFirst(Query.query(where("_id").is(objectId.toHexString() + "x")), new Update().set("foo", "bar"), "testcol");
}
2023-08-07T14:15:12.282+02:00 DEBUG 15565 --- [ main] o.s.data.mongodb.core.MongoTemplate : Calling update using query: { "_id" : { "$oid" : "64d0e050450ebf73e850fafc"}} and update: { "$set" : { "foo" : "bar"}} in collection: testcol
2023-08-07T14:15:12.287+02:00 DEBUG 15565 --- [ main] o.s.data.mongodb.core.MongoTemplate : Calling update using query: { "_id" : { "$oid" : "64d0e050450ebf73e850fafc"}} and update: { "$set" : { "foo" : "bar"}} in collection: testcol
2023-08-07T14:15:12.289+02:00 DEBUG 15565 --- [ main] o.s.data.mongodb.core.MongoTemplate : Calling update using query: { "_id" : "64d0e050450ebf73e850fafcx"} and update: { "$set" : { "foo" : "bar"}} in collection: testcol
When the records are effectively using "String" as datatype for _id, then the second query will not update the records. I would expect the update to keep the original data type.
We have been converting ObjectId's that are strings into real one since our inception. Check out the documentation on ID field handling and conversion to find an option that works for you best.
Thanks for the information. Having read the documentation I can respect the choice, but it appears the conversion is not applied when inserting a document (perhaps because we're using bson directly in this case?)
The following code prints out 0 twice:
@Test
void mongoObjectIdConversion() {
ObjectId objectId = ObjectId.get();
Document document = new Document("_id", objectId.toHexString());
mongoTemplate.insert(document, "testcol");
System.out.println(mongoTemplate.count(Query.query(where("_id").is(objectId)), "testcol"));
System.out.println(mongoTemplate.count(Query.query(where("_id").is(objectId.toHexString())), "testcol"));
}
Thanks for the sample code. Indeed, in that context, our conversion isn't intuitive. Let me take this concern to the team so we can further investigate how to improve usability.