title: How do you save a Python object into pymongo? (i.e. what method/return value do I need to override)
body: <p>Let's say I have a class: <code>TestClass</code>. This class is slotted.</p>
  
  <pre><code>class TestClass(object):
      __slots__ = ('_id', 'value1', 'value2',)
  </code></pre>
  
  <p>So we create an object.</p>
  
  <pre><code>test = TestClass()
  test.key1 = 'val1'
  test.key2 = 'val2'
  </code></pre>
  
  <p>Great! Now what I would like to do is insert <code>test</code> into a MongoDB instance.</p>
  
  <p><code>db.test_collection.insert(test)</code></p>
  
  <p>Uh oh.</p>
  
  <p><code>TypeError: 'TestClass' object is not iterable</code></p>
  
  <p>Ok, let's make that iterable.</p>
  
  <pre><code>class TestClass(object):
      __slots__ = ('_id', 'key1', 'key2',)
  
      def __iter__(self):
          yield from dict(
              (slot, self.__getattribute__(slot))
              for slot in self.__slots__).items()
  
  test = TestClass()
  test.key1 = 'val1'
  test.key2 = 'val2'
  
  for i in test:
      print(i)
  
  // result
  // ('key1', 'val1')
  // ('key2', 'val2')
  
  db.test_collection.insert(test)
  </code></pre>
  
  <p>This gives me: <code>doc['_id'] = ObjectId() // TypeError: 'tuple' object does not support item assignment</code>.</p>
  
  <p>Further, let's say I have a composition of objects...</p>
  
  <pre><code>test = TestClass()
  test.key1 = 'val1'
  test.key2 = TestClass()
  </code></pre>
  
  <p>Would the pymongo encoder be able to encode <code>test.key2</code> when saving <code>test</code>?</p>
  
  <p><strong>EDIT:</strong> I'm okay not saving the object directly and calling a function on the object like <code>test.to_document()</code>, but the goal is to have composite fields (e.g. <code>test.key2</code>) become a dict so that it can be saved.</p>