博客
关于我
MongoDB快速插入1000w测试数据(Java)
阅读量:798 次
发布时间:2023-02-09

本文共 2655 字,大约阅读时间需要 8 分钟。

MongoDB 数据插入优化指南

1. 添加 Maven 依赖

在项目中添加 MongoDB 驱动依赖,采用以下方式配置:

org.mongodb
mongodb-driver-sync
4.5.0

请根据实际需求选择最新版本。

2. 复制代码

以下是用于插入数据的完整 Java 类代码:

import com.mongodb.client.MongoClients;import com.mongodb.client.MongoClient;import com.mongodb.client.MongoDatabase;import com.mongodb.client.MongoCollection;import com.mongodb.client.model.Indexes;import org.bson.Document;import java.util.ArrayList;import java.util.List;import java.util.Random;public class MongoDBInsertTestData {    private static final String DATABASE_NAME = "test_database";    private static final String COLLECTION_NAME = "test_collection";    private static final int TOTAL_RECORDS = 100_000_000;    private static final int BATCH_SIZE = 10_000;    public static void main(String[] args) {        try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {            MongoDatabase database = mongoClient.getDatabase(DATABASE_NAME);            MongoCollection collection = database.getCollection(COLLECTION_NAME);            // 创建唯一索引            collection.createIndex(Indexes.ascending("id"));            insertData(collection);            System.out.println("Data insertion completed.");        }    }    private static void insertData(MongoCollection collection) {        Random random = new Random();        List
batch = new ArrayList<>(); for (int i = 0; i < TOTAL_RECORDS; i++) { Document doc = new Document("id", i) .append("name", generateRandomString(10)) .append("value", random.nextDouble()) .append("timestamp", System.currentTimeMillis()); batch.add(doc); if (batch.size() == BATCH_SIZE) { collection.insertMany(batch); System.out.println("Inserted " + batch.size() + " records."); batch.clear(); } } if (!batch.isEmpty()) { collection.insertMany(batch); System.out.println("Inserted " + batch.size() + " records."); } } private static String generateRandomString(int length) { StringBuilder sb = new StringBuilder(length); String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; Random random = new Random(); for (int i = 0; i < length; i++) { sb.append(characters.charAt(random.nextInt(characters.length()))); } return sb.toString(); }}

3. 修改配置并运行

在项目中添加上述依赖后,将代码复制到合适的位置,并确保以下配置正确:

  • pom.xml 中添加 MongoDB 依赖。
  • 修改 MongoDB 连接地址,确保 mongodb://localhost:27017 与你的本地 MongoDB 实例一致。

运行代码时,命令行执行 mvn clean run,即可开始插入测试数据。

转载地址:http://qnffk.baihongyu.com/

你可能感兴趣的文章
mysql 主从关系切换
查看>>
MYSQL 主从同步文档的大坑
查看>>
mysql 主键重复则覆盖_数据库主键不能重复
查看>>
MySQL 事务的面试题总结
查看>>
Mysql 事务知识点与优化建议
查看>>
Mysql 优化 or
查看>>
mysql 优化器 key_mysql – 选择*和查询优化器
查看>>
MySQL 优化:Explain 执行计划详解
查看>>
Mysql 会导致锁表的语法
查看>>
mysql 使用sql文件恢复数据库
查看>>
mysql 修改默认字符集为utf8
查看>>
Mysql 共享锁
查看>>
MySQL 内核深度优化
查看>>
mysql 内连接、自然连接、外连接的区别
查看>>
mysql 写入慢优化
查看>>
mysql 分组统计SQL语句
查看>>
Mysql 分页
查看>>
Mysql 分页语句 Limit原理
查看>>
MySql 创建函数 Error Code : 1418
查看>>
MySQL 创建新用户及授予权限的完整流程
查看>>