I am using java/morphia to deal with mongodb. The default ObjectId is not very convenient to use from Java layer. I would like to make it a String type while keep the key genera
You can use a string as an ID from Java too. Here is an example method and corresponding Unit test inserting one object with a string ID in a MongoDB collection:
public Document insert(String json, String collectionName) {
MongoCollection collection = database.getCollection(collectionName);
BasicDBObject document = BasicDBObject.parse(json);
Document doc = new Document(document);
collection.insertOne(doc);
return doc;
}
@Test
void whenInsert_ShouldInsertOne() {
final String uuid = UUID.randomUUID().toString();
final String collection = "test_collection";
final Document doc = app.insert(String.format("{\"_id\":\"%s\", \"name\": \"test\"}",
uuid), collection);
assertThat(doc).isNotNull();
final String json = app.getById(uuid, collection);
assertThat(json).contains(String.format("\"_id\": \"%s\"", uuid));
}