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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值