如何使用 PyMongo 将索引从一个集合复制到另一个集合?

snt*_*nth 5 python mongodb pymongo

在另一个问题(如何使用 PyMongo 将集合从一个数据库复制到同一服务器上的另一个数据库?)中,我弄清楚了如何将一个 MongoDB 集合复制到同一服务器上的另一个数据库。但是,这不会复制源集合上的索引,那么我如何复制这些索引呢?

snt*_*nth 5

因此使用简化的设置如下:

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

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

>>> 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}}
Run Code Online (Sandbox Code Playgroud)

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

client.db1.coll1.aggregate([{'$out':'coll2'}])
Run Code Online (Sandbox Code Playgroud)

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

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

我担心,由于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}}
Run Code Online (Sandbox Code Playgroud)


小智 3

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)
Run Code Online (Sandbox Code Playgroud)