【问题标题】:How do I copy the indexes from one collection to another collection using PyMongo?如何使用 PyMongo 将索引从一个集合复制到另一个集合?
【发布时间】:2023-03-13 12:25:02
【问题描述】:

在另一个问题 (How do I copy a collection from one database to another database on the same server using PyMongo?) 中,我想出了如何将一个 MongoDB 集合复制到同一服务器上的另一个数据库。但是,这不会复制源集合上的索引,那么我该如何复制这些索引呢?

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    所以使用如下简化设置:

    from pymongo import MongoClient
    client = MongoClient()
    client.db1.coll1.insert({'content':'hello world'})
    client.db1.coll1.create_index(keys='content')
    

    我们可以看到这有一个自定义索引:

    >>> client.db1.coll1.index_information()
    {u'_id_': {u'key': [(u'_id', 1)], u'ns': u'db1.coll1', u'v': 1},
     u'content_1': {u'key': [(u'content', 1)], u'ns': u'db1.coll1', u'v': 1}}
    

    然后我通过复制数据创建第二个集合coll2,如下所示:

    client.db1.coll1.aggregate([{'$out':'coll2'}])
    

    以下内容似乎适用于复制索引:

    for name, index_info in client.db1.coll1.index_information().iteritems():
        client.db1.coll2.create_index(keys=index_info['key'], name=name)
    

    我担心由于 coll2 已经有一个主键索引“_id”,这可能会导致错误,但它似乎是这样工作的:

    >>> client.db1.coll2.index_information()
    {u'_id_': {u'key': [(u'_id', 1)], u'ns': u'db1.coll2', u'v': 1},
     u'content_1': {u'key': [(u'content', 1)], u'ns': u'db1.coll2', u'v': 1}}
    

    【讨论】:

      【解决方案2】:
      for name, index_info in db_1.collection_x.index_information().items():
          keys = index_info['key']
          del(index_info['ns'])
          del(index_info['v'])
          del(index_info['key'])
          db_2.collection_y.create_index(keys, name=name, **index_info)
      

      【讨论】:

        猜你喜欢
        • 2015-10-23
        • 1970-01-01
        • 2017-02-08
        • 2021-06-14
        • 1970-01-01
        • 2021-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多