我刚开始使用 MongoDb,我注意到我得到了很多重复的记录,这些记录是我想要唯一的。我想知道如何为我的数据使用复合键,我正在寻找有关如何创建它们的信息。最后,我使用 Java 来访问 mongo 和 morphia 作为我的 ORM 层,因此在您的答案中包含这些内容会很棒。
吗啡:http://code.google.com/p/morphia/
最佳答案
您也可以为 _id 字段使用对象。 _id 字段始终是唯一的。这样你就可以得到一个复合主键:
{ _id : { a : 1, b: 1} }
在创建这些 id 时要小心,键的顺序(示例中的 a 和 b)很重要,如果交换它们,它会被视为不同的对象。
另一种可能性是不理会_id 和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/
https://stackoverflow.com/questions/7222062/