使用PyMongo如何使用create_index()导入索引,这些索引是使用index_information()导出的?

时间:2015-07-07 21:01:15

标签: python mongodb pymongo

您需要对index_information()的输出做什么,以便可以使用create_index()或create_indexes()重新导入它?

>>> from pymongo import MongoClient
>>> client = MongoClient("mongodb://host1")
>>> db = client.MYDB
>>> collection = db.MYCOLLECTION
>>> index = db.provisioning.index_information()
>>> index
{u'_id_': {u'ns': u'MYDB.MYCOLLECTION', u'key': [(u'_id', 1)], u'v': 1}, u'Name_1': {u'unique': True, u'key': [(u'Name', 1)], u'v': 1, u'ns': u'MYDB.MYCOLLECTION', u'background': False}, u'MongoType_1': {u'key': [(u'MongoType', 1)], u'ns': u'MYDB.MYCOLLECTION', u'background': False, u'v': 1}}
>>> client2 = MongoClient("mongodb://host2")
>>> db2 = client2.MYDB
>>> collection2 = db2.MYCOLLECTION
>>> collection2.create_index(index)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 1161, in create_index
    keys = helpers._index_list(keys)
  File "/usr/lib64/python2.6/site-packages/pymongo/helpers.py", line 55, in _index_list
    raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
>>> collection2.create_indexes(index)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 1046, in create_indexes
    raise TypeError("indexes must be a list")
TypeError: indexes must be a list

1 个答案:

答案 0 :(得分:1)

尝试这个基本代码,这将迭代并将所有索引从一个集合添加到其他集合

from pymongo import MongoClient

client = MongoClient("mongodb://host1")
db = client.MYDB
collection = db.MYCOLLECTION
index = db.provisioning.index_information()

client2 = MongoClient("mongodb://host2")
db2 = client2.MYDB
collection2 = db2.MYCOLLECTION
for i in index.keys():
    name_index = index[i]['key'][0][0]
    order = index[i]['key'][0][1]
    collection2.create_index([(name_index, order)])