MongoDB学习笔记-解析jsonCommand内容

如果需要屏蔽其他项目对MongoDB的直接访问操作,统一由一个入口访问操作MongoDB,可以考虑直接传入jsonCommand语句解析执行。
  • 相关依赖包
typescript 复制代码
<!-- SpringBootDataMongodb依赖包 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
    <version>2.4.2</version>
</dependency>
  • 部分代码
java 复制代码
    @Resource
    protected MongoProperties mongoProperties;

    public List<Map<String, Object>> readList(String mongoTemplateName, String collectionName, String jsonCommand)
            throws BusinessException {
        ParamUtils.checkParams(mongoTemplateName, collectionName, jsonCommand);
        List<Document> documentList = executeCommand(mongoTemplateName, collectionName, jsonCommand);
        if (null == documentList || documentList.isEmpty()) {
            return new ArrayList<>();
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Document currentDocument : documentList) {
            Map<String, Object> result = new HashMap<>();
            for (Map.Entry<String, Object> entry : currentDocument.entrySet()) {
                result.put(entry.getKey(), entry.getValue());
            }
            resultList.add(result);
        }
        return resultList;
    }

    private List<Document> executeCommand(String mongoTemplateName, String collectionName, String jsonCommand) {
        return mongoTemplateCache.get(mongoTemplateName)
                .withSession(ClientSessionOptions.builder().build()).execute(session -> {

            long startTimeMillis = System.currentTimeMillis();

            List<Document> allDocuments = new ArrayList<>();

            Document initialDocument = session.executeCommand(jsonCommand);
            Document cursorDocument = initialDocument.get("cursor", Document.class);
            List<Document> firstBatchDocuments = cursorDocument.getList("firstBatch", Document.class);
            if (null != firstBatchDocuments && !firstBatchDocuments.isEmpty()) {
                allDocuments.addAll(firstBatchDocuments);
            }

            Long cursorId = cursorDocument.getLong("id");
            while (null != cursorId && cursorId != 0) {
                try {
                    Document nextBatchCommand = new Document("getMore", cursorId).append("collection", collectionName)
                        .append("batchSize", mongoProperties.getDocumentBatchSize());
                    Document nextBatchResult = session.executeCommand(nextBatchCommand);
                    Document nextCursorDocument = nextBatchResult.get("cursor", Document.class);
                    List<Document> nextBatchDocuments = nextCursorDocument.getList("nextBatch", Document.class);
                    if (null != nextBatchDocuments && !nextBatchDocuments.isEmpty()) {
                        allDocuments.addAll(nextBatchDocuments);
                    }
                    cursorId = nextCursorDocument.getLong("id");
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    break;
                }
            }

            executionSqlLog(mongoTemplateName, collectionName, jsonCommand, startTimeMillis);

            return allDocuments;
        });
    }

    private void executionSqlLog(String mongoTemplateName, String collectionName, String jsonCommand,
            long startTimeMillis) {
        if (!mongoProperties.isExecutionSqlEnable()) {
            return;
        }
        long spendTime = System.currentTimeMillis() - startTimeMillis;
        log.info(
            "\n==============  SQL START  ==============" +
            "\nExecution MON :{} {} [{} ms]" +
            "\nExecution SQL :{}" +
            "\n==============  SQL END    ==============\n", mongoTemplateName, collectionName,
                spendTime, jsonCommand.replaceAll("\\s{2,}", " "));
    }

}
相关推荐
二哈喇子!1 小时前
Java开发工具——IDEA(修改全局配置,提升工作效率)
java·编辑器·intellij-idea
强子感冒了1 小时前
Java网络编程学习笔记,从网络编程三要素到TCP/UDP协议
java·网络·学习
二哈喇子!1 小时前
SpringBoot项目右上角选择ProjectNameApplication的配置
java·spring boot
sin22011 小时前
MyBatis的执行流程
java·开发语言·mybatis
二哈喇子!1 小时前
基于Spring Boot框架的车库停车管理系统的设计与实现
java·spring boot·后端·计算机毕业设计
二哈喇子!1 小时前
基于Spring Boot框架的网络游戏虚拟交易平台的设计与实现
java·springboot·毕设项目
二哈喇子!2 小时前
JAVA环境变量配置步骤及测试(JDK的下载 & 安装 & 环境配置教程)
java·开发语言
二哈喇子!2 小时前
Java框架精品项目【用于个人学习】
java·spring boot·学习
二哈喇子!2 小时前
基于SpringBoot框架的网上购书系统的设计与实现
java·大数据·spring boot
Mixtral2 小时前
2026年4款学习转写工具测评:告别逐字整理,自动生成复习资料
笔记·学习·ai·语音转文字