1

I'm using Spring-data to map pojos to mongo json documents.

The mongo Object Id reference 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?

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).

Here is an example:

@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
}

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.

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).

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?

this.id = yyyymmdd + uniqueStudentName.toLowerCase();   
rallison
  • 199
  • 2
  • 3
  • 9

1 Answers1

1

It is certainly reasonable to use a combination of attributes as a primary key. However, rather than concatenating them, it is probably more logically intuitive to place them into a subdocument with two fields (uniqueStudentName and yyyymmdd) that is used as the _id.

Take a look at this question, which involves using a compound primary key:

MongoDB Composite Key

Community
  • 1
  • 1
shelman
  • 2,689
  • 15
  • 17
  • Thanks! I didn't know to search for 'composite key', so I missed the question you provided. Ultimately, I think the extra Java class, just to use it as an ID, doesn't seem to be what they mean when the mongo folks suggest using a natural primary key if there is one. I guess I'll go with the mongo-assigned ID and a unique compound index on unuqueStudentName and yyyymmdd. – rallison Oct 09 '12 at 06:58