我有以下代码来设置数据库:
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()
显示新索引。这是否意味着我必须等到集合中有条目之后才能创建索引?自从一个空集合开始以来,还有另一种方法吗?
您可以在一个空的或不存在的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调用异步方法的讨论(这不仅适用于Motor,而且适用于所有Tornado库),从“插入文档”部分开始。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句