4

In another question (How do I copy a collection from one database to another database on the same server using PyMongo?) I figured out how to copy one MongoDB collection to another database on the same server. However this doesn't copy the indexes on the source collection so how do I copy those?

Community
  • 1
  • 1
snth
  • 5,194
  • 4
  • 39
  • 48

2 Answers2

4

So using a simplified setup as follows:

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

We can see that this has a custom index:

>>> 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}}

I then create a second collection coll2 by copying the data as follows:

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

The following then appears to work for copying the index:

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

I was concerned that since coll2 would already have a primary key index '_id', this might cause an error but it appears to have worked just like that:

>>> 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}}
snth
  • 5,194
  • 4
  • 39
  • 48
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)
klolik
  • 46
  • 1