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 分钟前
kafka总结
java
诗句藏于尽头8 分钟前
内网使用rustdesk搭建远程桌面详细版
笔记
蜡笔小电芯8 分钟前
【C语言】指针与回调机制学习笔记
c语言·笔记·学习
丰锋ff21 分钟前
瑞斯拜考研词汇课笔记
笔记
yanjiaweiya29 分钟前
云原生-集群管理
java·开发语言·云原生
gadiaola38 分钟前
【JavaSE面试篇】Java集合部分高频八股汇总
java·面试
艾迪的技术之路1 小时前
redisson使用lock导致死锁问题
java·后端·面试
今天背单词了吗9801 小时前
算法学习笔记:8.Bellman-Ford 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·后端·算法·最短路径问题
天天摸鱼的java工程师1 小时前
使用 Spring Boot 整合高德地图实现路线规划功能
java·后端