MongoDB Composite Key

You can use objects for the _id field as well. The _id field is always unique. That way you kind of get a composite primary key:

 { _id : { a : 1, b: 1} }

Just be careful when creating these ids that the order of keys (a and b in the example) matters, if you swap them around, it is considered a different object.

The other possibility is to leave _id alone and create a unique compound index.

db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
//Deprecated since version 3.0.0, is now an alias for db.things.createIndex()

https://docs.mongodb.org/v3.0/reference/method/db.collection.ensureIndex/

Leave a Comment