gpt4 book ai didi

python - 使用 PyMongo,如何使用 create_index() 导入通过 index_information() 导出的索引?

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:16 26 4
gpt4 key购买 nike

您需要对 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

最佳答案

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

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)])

关于python - 使用 PyMongo,如何使用 create_index() 导入通过 index_information() 导出的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31279175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com