2
在另一个问题(How do I copy a collection from one database to another database on the same server using PyMongo?)我想出了如何将一个MongoDB集合复制到同一台服务器上的另一个数据库。但是,这不会复制源集合中的索引,因此如何复制这些索引?如何使用PyMongo将索引从一个集合复制到另一个集合?
在另一个问题(How do I copy a collection from one database to another database on the same server using PyMongo?)我想出了如何将一个MongoDB集合复制到同一台服务器上的另一个数据库。但是,这不会复制源集合中的索引,因此如何复制这些索引?如何使用PyMongo将索引从一个集合复制到另一个集合?
所以使用简化的设置如下:
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}}