Mongodb dynamic table creation scheme (official native driver)

Time:2021-8-12

Mongodb dynamic table creation scheme (official native driver)

Requirement premise: table name is dynamic, table structure is static, and library is fixed

1. Import related dependencies

org.mongodb
    mongodb-driver
    3.11.2


	org.mongodb
	bson
	3.11.2


    org.mongodb
    mongodb-driver-core
    3.11.2

2. Defining entities

@Data
public class Person {
    private String name;
    private int sex;
    private String address;
}

3. Set entity parser

public static void addMongoDB(String collectionName) {
        CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));
        MongoClient mongoClient = MongoClients.create("mongodb://admin:Tong#[email protected]:15700");
        //Specify entity parser
        MongoDatabase mongoDatabase = mongoClient.getDatabase("marty_test").withCodecRegistry(pojoCodecRegistry);
        MongoCollection mongoCollection = mongoDatabase.getCollection(collectionName, Person.class);
        Person person = new Person();
        person.setName("test");
        Person.setaddress ("address");
        person.setSex(1);
        mongoCollection.insertOne(person);
    }

Note: after the collection is obtained, it will be automatically created when inserting data for the first time, and the database is similar

4. Test

public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10; i++) {
            addMongoDB("test-" + i);
        }
    }

Recommended Today

The simplest thing in investment

Self cultivation of leek I recently read the simplest thing in investment. I feel the content is good. Here is a record to improve the self-cultivation of leek. Lu Xun once said: “as long as people have money, their troubles will be reduced by more than 90%, their EQ and IQ will be improved, and […]