title: Using Spring-Data and mongodb, natural vs. artificial id?
body: <p>I'm using Spring-data to map pojos to mongo json documents.</p>
  
  <p>The mongo Object Id <a href="http://www.mongodb.org/display/DOCS/Object+IDs" rel="nofollow">reference</a> says "If your document has a natural primary key that is immutable we recommend you use that in _id instead of the automatically generated ids."  My question is, if my document has a natural primary key but it is some combination of the object's attributes, should I combine them to create the natural primary key?</p>
  
  <p>Assume that neither of the values can ever change, and when concatenated together the result is guaranteed to be unique.  Note that whatever type you declare for id, Spring converts it to an ObjectId (unless they don't have a converter for that type, then they convert it to a String).   </p>
  
  <p>Here is an example:</p>
  
  <pre><code>@Document
  public Class HomeworkAssignment {
  
      @Id
      private String id;
  
      private final String yyyymmdd;
  
      private final String uniqueStudentName;
  
      private double homeworkGrade; 
  
      public HomeworkAssignment(String yyyymmdd, String uniqueStudentName) {
          this.yyyymmdd = yyyymmdd;
          this.uniqueStudentName = uniqueStudentName;
          // can either set the 'id' here, or let Spring give me an artificial one.
      }
  
      // setter provided for the homeworkGrade
  }
  </code></pre>
  
  <p>There is guaranteed to be no more than one homework assignment per student per day.  Both yyyymmdd and uniqueStudentName are given to me as Strings.</p>
  
  <p>For example, "20120601bobsmith" uniquely identifies Bob Smith's homework on June 1, 2012.  (If there is more than one Bob Smith, it is already handled in the uniqueName I'm given).  </p>
  
  <p>Assume that I want to follow the mongo reference advice and use a natural primary key if there is one.  There is one, but it is a combination of 2 fields.  Is this a case where I should combine them like so?</p>
  
  <pre><code>this.id = yyyymmdd + uniqueStudentName.toLowerCase();   
  </code></pre>