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

}
相关推荐
数据潜水员16 分钟前
C#基础语法
java·jvm·算法
你这个代码我看不懂37 分钟前
Java项目OOM排查
java·开发语言
Zong_09151 小时前
AutoCompose - 携程自动编排【开源】
java·spring boot·开源·自动编排
东京老树根1 小时前
SAP学习笔记 - 开发18 - 前端Fiori开发 应用描述符(manifest.json)的用途
笔记·学习
.生产的驴1 小时前
SpringCloud 分布式锁Redisson锁的重入性与看门狗机制 高并发 可重入
java·分布式·后端·spring·spring cloud·信息可视化·tomcat
虾球xz2 小时前
CppCon 2014 学习:C++ Memory Model Meets High-Update-Rate Data Structures
java·开发语言·c++·学习
攒了一袋星辰2 小时前
Spring @Autowired自动装配的实现机制
java·后端·spring
m0_678693332 小时前
深度学习笔记25-RNN心脏病预测(Pytorch)
笔记·rnn·深度学习
我的golang之路果然有问题2 小时前
快速了解GO+ElasticSearch
开发语言·经验分享·笔记·后端·elasticsearch·golang
Bug缔造者2 小时前
若依+vue2实现模拟登录
java·前端框架