MongoDB 以json执行命令及原理分析

背景描述

最近参加了公司的一个效能平台的开发,用到了MongoDB。

由于不想频繁提交sql执行工单,因此弄了个sql执行的后台。
使用Spring data框架携带的Mongodb工具,org.springframework.data.mongodb.core.MongoTemplate的executeCommand(String jsonCommand)作为执行的核心方法。

但是做了大量的查询,也没找到对应操作如何以json去执行,为此做下记录。

好吧,我找到了mongodb的命令的定义了,可以查看MongoDB命令

注意版本

spring-boot-1.5.8.RELEASE
mongo-java-driver-3.4.3
spring-data-mongodb-1.10.23.RELEASE

一些操作的例子

insert

{
    "insert":"test",	// 操作:集合
    "documents":[		// 需要插入的文档数组
        {
            "_id":1,
            "name":"zhou"
        },
        {
            "_id":2,
            "name":"2"
        }
    ]
}

update

{
    "update":"test",
    "updates":[
        {
            "q":{	// q代表query
                "name":"zhou"
            },
            "u":{	// u代表update
                "name":"fucQ"
            }
        },
        {
            "q":{
                "name":"2"
            },
            "u":{
                "name":"22"
            }
        }
    ]
}

create index

{
	"createIndexes": "test",
    "requests": [
        {
            "keys": "name",
            "unique": true
        }
    ]
}

分析

com.mongodb.operation 中存在的operation类,对应着Mongodb下的操作。
在这里插入图片描述

// 创建一个或多个索引操作
// 多个索引创建需要 MongoDB server version 2.6+
public class CreateIndexesOperation implements AsyncWriteOperation<Void>, WriteOperation<Void> {
    private final MongoNamespace namespace;
    private final List<IndexRequest> requests;
    private final WriteConcern writeConcern;
    private final MongoNamespace systemIndexes;

    public CreateIndexesOperation(final MongoNamespace namespace, final List<IndexRequest> requests, final WriteConcern writeConcern) {
        this.namespace = notNull("namespace", namespace);
        this.systemIndexes = new MongoNamespace(namespace.getDatabaseName(), "system.indexes");
        this.requests = notNull("indexRequests", requests);
        this.writeConcern = writeConcern;
    }

    // 多个索引创建
    public List<String> getIndexNames() {
        List<String> indexNames = new ArrayList<String>(requests.size());
        for (IndexRequest request : requests) {
            if (request.getName() != null) {
                indexNames.add(request.getName());
            } else {
                indexNames.add(IndexHelper.generateIndexName(request.getKeys()));
            }
        }
        return indexNames;
    }

	// 提取请求的json中特定的字段,拼接为mongodb的命令
	// 因此,json所支持的字段都可以在此处找到
	// 也可以直接查看 com.mongodb.bulk.IndexRequest
    private BsonDocument getIndex(final IndexRequest request) {
        BsonDocument index = new BsonDocument();
        index.append("key", request.getKeys());
        index.append("name", new BsonString(request.getName() != null ? request.getName() : generateIndexName(request.getKeys())));
        index.append("ns", new BsonString(namespace.getFullName()));
        if (request.isBackground()) {
            index.append("background", BsonBoolean.TRUE);
        }
        if (request.isUnique()) {
            index.append("unique", BsonBoolean.TRUE);
        }
        if (request.isSparse()) {
            index.append("sparse", BsonBoolean.TRUE);
        }
        if (request.getExpireAfter(TimeUnit.SECONDS) != null) {
            index.append("expireAfterSeconds", new BsonInt64(request.getExpireAfter(TimeUnit.SECONDS)));
        }
        if (request.getVersion() != null) {
            index.append("v", new BsonInt32(request.getVersion()));
        }
        if (request.getWeights() != null) {
            index.append("weights", request.getWeights());
        }
        if (request.getDefaultLanguage() != null) {
            index.append("default_language", new BsonString(request.getDefaultLanguage()));
        }
        if (request.getLanguageOverride() != null) {
            index.append("language_override", new BsonString(request.getLanguageOverride()));
        }
        if (request.getTextVersion() != null) {
            index.append("textIndexVersion", new BsonInt32(request.getTextVersion()));
        }
        if (request.getSphereVersion() != null) {
            index.append("2dsphereIndexVersion", new BsonInt32(request.getSphereVersion()));
        }
        if (request.getBits() != null) {
            index.append("bits", new BsonInt32(request.getBits()));
        }
        if (request.getMin() != null) {
            index.append("min", new BsonDouble(request.getMin()));
        }
        if (request.getMax() != null) {
            index.append("max", new BsonDouble(request.getMax()));
        }
        if (request.getBucketSize() != null) {
            index.append("bucketSize", new BsonDouble(request.getBucketSize()));
        }
        if (request.getDropDups()) {
            index.append("dropDups", BsonBoolean.TRUE);
        }
        if (request.getStorageEngine() != null) {
            index.append("storageEngine", request.getStorageEngine());
        }
        if (request.getPartialFilterExpression() != null) {
            index.append("partialFilterExpression", request.getPartialFilterExpression());
        }
        if (request.getCollation() != null) {
            index.append("collation", request.getCollation().asDocument());
        }
        return index;
    }

    private BsonDocument getCommand(final ConnectionDescription description) {
        BsonDocument command = new BsonDocument("createIndexes", new BsonString(namespace.getCollectionName()));
        List<BsonDocument> values = new ArrayList<BsonDocument>();
        for (IndexRequest request : requests) {
        	// 创建单个索引的参数
            values.add(getIndex(request));
        }
        command.put("indexes", new BsonArray(values));
        appendWriteConcernToCommand(writeConcern, command, description);
        return command;
    }
}

通过对创建索引操作类的分析,可以分析出对应的json格式

{
    "createIndexes": "test",	// 操作 操作的集合
    "requests": [				// 命令的数据,会在解析过程中被转换为BsonDocument对象
        {
            "keys": ["name"],   // 建立的字段
            "name": "idx_name", // 索引的名字
            "unique": true, // 是否唯一索引
            "weights": 1    // 索引权重
        }
    ]
}

然后通过类似操作类的比较分析,可以大致得到

{
    "{operation}": "{collection}",	// 操作 操作的集合
    "{opParamsList}": [
        {
            "{name}": "{val}"
        }
    ]
}

有些特殊的情况在于大块的操作需要结合org.springframework.data.mongodb.core.DefaultBulkOperations 类,比如对于插入个文档{opParamsList}是document,而插入多个,{opParamsList}是documents。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咕咕咕zhou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值