title: How to be avoid duplicates entries at insert to MongoDB
body: <p>I just want to be shure when inputting new DBObject to DB that it is really unique and Collection doesn't contain key field duplicates .</p>
  
  <p>Here is how it looks now:</p>
  
  <pre><code>public abstract class AbstractMongoDAO&lt;ID, MODEL&gt; implements GenericDAO&lt;ID, MODEL&gt; {
  
      protected Mongo client;
  
      protected Class&lt;MODEL&gt; model;
  
      protected DBCollection dbCollection;
  
      /**
       * Contains model data : unique key name and name of get method
       */
      protected KeyField keyField;
  
      @SuppressWarnings("unchecked")
      protected AbstractMongoDAO() {
          ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
          model = (Class&lt;MODEL&gt;) genericSuperclass.getActualTypeArguments()[1];
          getKeyField();
      }
  
      public void connect() throws UnknownHostException {
          client = new MongoClient(Config.getMongoHost(), Integer.parseInt(Config.getMongoPort()));
          DB clientDB = client.getDB(Config.getMongoDb());
          clientDB.authenticate(Config.getMongoDbUser(), Config.getMongoDbPass().toCharArray());
          dbCollection = clientDB.getCollection(getCollectionName(model));
      }
  
      public void disconnect() {
          if (client != null) {
              client.close();
          }
      }
  
      @Override
      public void create(MODEL model) {
          Object keyValue = get(model);
          try {
              ObjectMapper mapper = new ObjectMapper();
              String requestAsString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(model);
              // check if not presented
              BasicDBObject dbObject = new BasicDBObject((String) keyValue, requestAsString);
              dbCollection.ensureIndex(dbObject, new BasicDBObject("unique", true));
              dbCollection.insert(new BasicDBObject((String) keyValue, requestAsString));
          } catch (Throwable e) {
              throw new RuntimeException(String.format("Duplicate parameters '%s' : '%s'", keyField.id(), keyValue));
          }
      }
  
  private Object get(MODEL model) {
      Object result = null;
      try {
          Method m = this.model.getMethod(this.keyField.get());
          result = m.invoke(model);
      } catch (Exception e) {
          throw new RuntimeException(String.format("Couldn't find method by name '%s' at class '%s'", this.keyField.get(), this.model.getName()));
      }
      return result;
  }
  
  /**
   * Extract the name of collection that is specified at '@Entity' annotation.
   *
   * @param clazz is model class object.
   * @return the name of collection that is specified.
   */
  private String getCollectionName(Class&lt;MODEL&gt; clazz) {
      Entity entity = clazz.getAnnotation(Entity.class);
      String tableName = entity.value();
      if (tableName.equals(Mapper.IGNORED_FIELDNAME)) {
          // think about usual logger
          tableName = clazz.getName();
      }
      return tableName;
  }
  
  private void getKeyField() {
      for (Field field : this.model.getDeclaredFields()) {
          if (field.isAnnotationPresent(KeyField.class)) {
              keyField = field.getAnnotation(KeyField.class);
              break;
          }
      }
      if (keyField == null) {
          throw new RuntimeException(String.format("Couldn't find key field at class : '%s'", model.getName()));
      }
  }
  </code></pre>
  
  <p><strong><em>KeyFeld</em></strong> is custom annotation:</p>
  
  <pre><code>@Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.FIELD)
  public @interface KeyField {
  
      String id();
  
      String get();
  
      String statusProp() default "ALL";
  </code></pre>
  
  <p>But I'm not shure that this solution really prove this. I'm newly at Mongo.</p>
  
  <p><strong><em>Any suggestions?</em></strong></p>