2017-02-15 6 views
2

別の質問(How do I copy a collection from one database to another database on the same server using PyMongo?)で、同じサーバー上の別のデータベースに1つのMongoDBコレクションをコピーする方法を理解しました。しかし、これはソースコレクションのインデックスをコピーしないので、どのようにコピーするのですか?PyMongoを使用してあるコレクションから別のコレクションにインデックスをコピーするにはどうすればよいですか?

答えて

2

次のように単純化された設定を使用して:

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

次のように私は、データをコピーすることにより、第2のコレクション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}} 
関連する問題