Can I use String as ID type for mongodb document?

前端 未结 5 2021
死守一世寂寞
死守一世寂寞 2021-02-18 17:11

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

5条回答
  •  情歌与酒
    2021-02-18 17:40

    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));
    }
    

提交回复
热议问题