1

我有以下代码来设置我的数据库:

self.con = motor.MotorClient(host, port)
self.Db = self.con.DB
self.Col = self.Db.Col

self.Col.create_index("c")
self.Col.create_index("h")

当我运行时,index_information()我只看到 _id 字段的索引信息。但是,如果我在create_index()插入一些条目后移动,则会index_information()显示新索引。这是否意味着我必须等到集合中有条目才能创建索引?自从我从一个空集合开始以来,还有其他方法可以做到这一点吗?

4

2 回答 2

2

可以在空的或不存在的 MongoDB 集合上创建索引,该索引出现在index_information

>>> from tornado import ioloop, gen
>>> import motor
>>>
>>> con = motor.MotorClient()
>>> db = con.test
>>> col = db.collection
>>>
>>>
>>> @gen.coroutine
... def coro():
...     yield db.drop_collection("collection")
...     yield col.create_index("c")
...     yield col.create_index("h")
...     print((yield col.index_information()))
...
>>> ioloop.IOLoop.current().run_sync(coro)
{u'c_1': {u'key': [(u'c', 1)], u'v': 1}, u'_id_': {u'key': [(u'_id', 1)], u'v': 1}, u'h_1': {u'key': [(u'h', 1)], u'v': 1}}

由于我在您的示例代码中没有看到任何“yield”语句或任何回调,我怀疑您没有正确使用 Motor。电机是异步的;为了等待与数据库服务器对话的任何 Motor 方法完成,您必须将回调传递给该方法,或者产生该方法返回的 Future。

有关更多信息,请参阅教程:

http://motor.readthedocs.org/en/stable/tutorial.html#inserting-a-document

关于使用 Motor 调用异步方法的讨论(这适用于所有 Tornado 库,而不仅仅是 Motor)从“插入文档”部分开始。

于 2015-11-01T21:45:50.717 回答
0

field_name您可以使用and非常轻松地在 mongodb(甚至在空集合上)上创建索引 direction

field_name:可以是您要在其上创建索引的任何字段。
direction:可以是以下值中的任何一个:1, -1, 2dsphere,texthashed

有关详细信息,请参阅 MotorCollection 文档

在下面的代码中,我尝试使用motor库和python.

db.collection_name.create_index([("field_name", 1)] # To create ascending index
db.collection_name.create_index([("geoloc_field_name", "2dsphere")] # To create geo index
db.collection_name.create_index([("field_name", "text")] # To create text based index
于 2022-02-15T10:54:41.250 回答