title: MongoDB: How to insert document in collection that exists in other collection as well?
body: <p>I have two collections <code>EN_PR2019</code> and <code>EN_PR2018</code>. They mosty contain the same things but from different years. After inserting all the documents into <code>EN_PR2019</code> I'm trying to insert documents that may have the same <code>_id</code> as in collection <code>EN_PR2019</code>. I read that I needed to create a index for the collection to be able to have records with the same <code>_id</code> in two different collections. Right now I'm getting <code>pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: Database.EN_PR2018 index: id_1 dup key: { id: null }</code>.</p>
  
  <p>How do I insert the same record, having the same <code>_id</code> in two different collections without raising errors or having to deal with duplicates?</p>
  
  <pre class="lang-py prettyprint-override"><code>def check_record(collection, record_id):
      """Check if record exists in collection
          Args:
              record_id (str): record _id as in collection
      """
      return collection.find_one({'id': record_id})
  
  def collection_index(collection, index):
      """Checks if index exists for collection, 
      and return a new index if not
  
          Args:
              collection (str): Name of collection in database
              index (str): Dict key to be used as an index
      """
      if index not in collection.index_information():
          return collection.create_index([(index, pymongo.ASCENDING)], unique=True)
  
  def push_upstream(collection, record_id, record):
      """Update record in collection
          Args:
              collection (str): Name of collection in database
              record_id (str): record _id to be put for record in collection
              record (dict): Data to be pushed in collection
      """
      return collection.insert_one({"_id": record_id}, {"$set": record})
  
  def update_upstream(collection, record_id, record):
      """Update record in collection
          Args:
              collection (str): Name of collection in database
              record_id (str): record _id as in collection
              record (dict): Data to be updated in collection
      """
      return collection.update_one({"_id": record_id}, {"$set": record}, upsert=True)
  
  def executePushPlayer(db):
  
      playerstats = load_file(db.playerfile)
      collection = db.DATABASE[db.league + db.season]
      collection_index(collection, 'id')
      for player in playerstats:
          existingPost = check_record(collection, player['id'])
          if existingPost:
              update_upstream(collection, player['id'], player)
          else:
              push_upstream(collection, player['id'], player)
  
  if __name__ == '__main__':
      test = DB('EN_PR', '2018')
      executePushPlayer(test)
  
  </code></pre>