MongoDB复合键 [英] MongoDB Composite Key
问题描述
我刚刚开始使用MongoDb,我注意到我获得了许多重复记录,我认为这些记录是独一无二的。我想知道如何为我的数据使用复合键,我正在寻找有关如何创建它们的信息。最后,我使用Java来访问mongo和morphia作为我的ORM层,所以在你的答案中包括那些将是很棒的。
I'm just getting started with MongoDb and I've noticed that I get a lot of duplicate records for entries that I meant to be unique. I would like to know how to use a composite key for my data and I'm looking for information on how to create them. Lastly, I am using Java to access mongo and morphia as my ORM layer so including those in your answers would be awesome.
Morphia: http://code.google.com/p/morphia/
推荐答案
您也可以将对象用于_id字段。 _id字段始终是唯一的。这样你就得到了一个复合主键:
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} }
创建这些ID时要小心,键的顺序(示例中的a和b)很重要,如果你交换它们,它被认为是一个不同的对象。
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.
另一种可能性是单独留下_id和创建一个独特的复合索引。
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 /
这篇关于MongoDB复合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!