python实现mongo只迁移表结构和索引

在某些业务场景,我们或许只迁移部分表的数据,大部分都是迁移表结构和索引,这种如何实现,如下:

#coding=utf-8
import subprocess
import pymongo

path_indexs = '/home/indexs/'
path_table_structure = '/home/table_structure/'
mongo_client = pymongo.MongoClient(host="127.0.0.1", port=27017, connect=True)
mongo_dbs = mongo_client.database_names()

#迁移索引
fun_index = """
db.getCollectionNames().forEach(function (col) {
    if (!db[col]) return;
    var indexes = db[col].getIndexes();
    indexes.forEach(function (c) {
        var fields = '', result = '', options1 = {};
        for (var i in c) {
            if (i == 'key') {
                fields = c[i];
            } else if (i == 'name' && c[i] == '_id_') {
                return;
            } else if (i != 'name' && i != 'v' && i != 'ns') {
                options1[i] = c[i];
            }
        }
        var fields = JSON.stringify(fields);
        var options = JSON.stringify(options1);
        if (options == '{}') {
            result = \\"db.\\" + col + \\".createIndex(\\" + fields + \\"); \\";
        } else {
            result = \\"db.\\" + col + \\".createIndex(\\" + fields + \\", \\" + options + \\"); \\";
        }
        result = result
            .replace(/{\\"floatApprox\\":-1,\\"top\\":-1,\\"bottom\\":-1}/ig, '-1')
            .replace(/{\\"floatApprox\\":(-?\d+)}/ig, '$1')
            .replace(/\{\\"\$numberLong\\":\\"(-?\d+)\\"\}/ig, '$1');
        print(result);
    });
});"""


#迁移表结构
fun_table_structure = """
db.getCollectionNames().forEach(function (col) {
    var runCommandStr = \\"\\";
    runCommandStr = \\"db.createCollection('\\" + col + \\"');\\"
    print(runCommandStr);
});
"""


def dump_mongo(path, dump):
    for db in mongo_dbs:
        print "正在生成{}库文件,请稍等".format(db)
        cmd = 'mongo {} --eval "{}"'.format(db, dump)
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        res = p.stdout.read()
        with open('{}{}.txt'.format(path, db), 'wb') as f:
            f.write(res)


if __name__ == '__main__':
    dump_mongo(path_table_structure, fun_table_structure)
    dump_mongo(path_indexs, fun_index)
    subprocess.Popen('tar -czvf mongo_migrate.tar.gz {} {}'.format(path_indexs, path_table_structure), shell=True)

这里,我们得到了创建mongo表结构和索引的语句,通过读取该txt文件,一个循环执行语句,我们就可以还原数据库了

 

MongoDB 中,可以使用 `$lookup` 操作符进行多查询。以下是一个使用 Python 和 PyMongo实现查询的示例: 假设有两个集合:`orders` 和 `customers`。`orders` 集合包含订单信息,而 `customers` 集合包含客户信息。每个订单文档都包含一个 `customer_id` 字段,该字段指向客户集合中的客户文档。 现在我们想要获取每个订单的客户信息,可以使用 `$lookup` 操作符将 `orders` 集合与 `customers` 集合关联起来。 以下是示例代码: ```python from pymongo import MongoClient client = MongoClient() db = client['my_database'] orders = db['orders'] customers = db['customers'] pipeline = [ { "$lookup": { "from": "customers", "localField": "customer_id", "foreignField": "_id", "as": "customer" } }, { "$unwind": "$customer" } ] result = orders.aggregate(pipeline) for order in result: print(order) ``` 在上面的代码中,我们定义了一个名为 `pipeline` 的管道,其中包含了一个 `$lookup` 操作符,它将 `orders` 集合与 `customers` 集合关联起来。`"$lookup"` 中的参数含义如下: - `"from"`:被关联的集合名称 - `"localField"`:当前集合中用于关联的字段 - `"foreignField"`:被关联集合中用于关联的字段 - `"as"`:输出结果中包含关联集合的字段名 接下来,我们使用 `aggregate()` 方法将管道应用于 `orders` 集合,并使用 `for` 循环遍历结果集。 最后,我们使用 `print()` 函数打印每个订单文档及其关联的客户文档。 注意:以上示例代码仅供参考,实际使用时需要根据具体情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值