当前位置: 首页 > article >正文

MongoDB学习笔记-解析jsonCommand内容

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

    @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,}", " "));
    }

}


http://www.kler.cn/a/534898.html

相关文章:

  • Linux 安装 RabbitMQ
  • 自指学习:AGI的元认知突破
  • VMware Workstation Pro安装了Ubuntu 24.04实现与Windows10之间的复制粘贴
  • 鸿蒙Harmony-双向数据绑定MVVM以及$$语法糖介绍
  • openRv1126 AI算法部署实战之——Tensorflow模型部署实战
  • 【Redis】主从模式,哨兵,集群
  • Unix/Linux编程:fcntl函数总结
  • vscode 如何通过Continue引入AI 助手deepseek
  • 国产编辑器EverEdit - 自定义标记使用详解
  • python爬虫--简单登录
  • 无界构建微前端?NO!NO!NO!多系统融合思路!
  • HTML 复习
  • [SAP ABAP] 面向对象程序设计-类的访问区域
  • 【React】合成事件语法
  • 防静电监控看板如何助力生产线提升品质管理效率
  • C语言基础系列【4】C语言基础语法
  • 深度剖析 C++17 中的 std::byte:解锁字节级编程新境界
  • PHP JSON操作指南
  • uniapp使用uts插件调用原生API
  • 鸿蒙 Next 开发实践:使用 WebView 适配移动端网站
  • JAVA异步的UDP 通讯-客户端
  • 云端IDE如何重定义开发体验
  • VS Code Python 开发环境配置
  • Linux环境下的事件驱动力量:探索Libevent的高性能IO架构
  • Java 中接口和抽象类的异同
  • Hive之数据操作DML