gpt4 book ai didi

java - MongoDB 组合键

转载 作者:IT老高 更新时间:2023-10-28 11:06:15 34 4
gpt4 key购买 nike

我刚开始使用 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/

关于java - MongoDB 组合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7222062/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com