title: How to create index in mongodb with pymongo
body: <p>I use scrapy crawl data and save it to mongodb, i want to save <code>2dsphere</code> index in mongodb.</p>
  
  <p>Here is my pipelines.py file with scrapy</p>
  
  <pre><code>from pymongo import MongoClient
  from scrapy.conf import settings
  
  class MongoDBPipeline(object):
  
      global theaters
      theaters = []
  
      def __init__(self):
          connection = MongoClient(
              settings['MONGODB_SERVER'],
              settings['MONGODB_PORT'])
          self.db = connection[settings['MONGODB_DB']]
          self.collection = self.db[settings['MONGODB_COLLECTION']]
  
      def open_spider(self, spider):
          print 'Pipelines =&gt; open_spider =&gt;'
  
      def process_item(self, item, spider):
  
          global theaters
          # get the class item name to be collection name
          self.collection = self.db[type(item).__name__.replace('_Item','')]
  
          if  item['theater'] not in theaters:
              print 'remove=&gt;',item['theater']
              theaters.append(item['theater'])
              self.collection.remove({'theater': item['theater']})
  
          # insert the collection name that is from class object item
          self.collection.insert(dict(item))
          # Here is what i try to create 2dsphere index
          self.collection.create_index({"location": "2dsphere"})
  
          return item
  </code></pre>
  
  <p>When i use <code>self.collection.create_index({"location": "2dsphere"})</code></p>
  
  <p>It shows error <code>TypeError: if no direction is specified, key_or_list must be an instance of list</code></p>
  
  <p>If i try </p>
  
  <pre><code>self.collection.create_index([('location', "2dsphere")], name='search_index', default_language='english')
  </code></pre>
  
  <p>There is no error any more , but my mongodb still hasn't any index under <code>location</code>.
  <a href="https://i.stack.imgur.com/FfPdQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FfPdQ.png" alt="enter image description here"></a></p>
  
  <p>I think i obey the GeoJson format.  </p>
  
  <p>Is any way to save <code>2dsphere</code> index in mongodb when i using <code>scrapy</code> ?  Or should i just save the data like the photo structure and save index by another server file (like <code>nodejs</code>)</p>
  
  <p>Any help would be appreciated. Thanks in advance.</p>
  
  <p>According to <code>Adam Harrison</code> respond, i try to change my mongodb name <code>location</code> to <code>geometry</code></p>
  
  <p>Than add code <code>import pymongo</code> in my pipelines.py file</p>
  
  <p>and use <code>self.collection.create_index([("geometry", pymongo.GEOSPHERE)])</code></p>
  
  <p>There is no any error but still can't find the index under <code>geometry</code>
  <a href="https://i.stack.imgur.com/tERhq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tERhq.png" alt="enter image description here"></a></p>