php小编西瓜为您介绍如何为Mongodb创建唯一的pair索引。Mongodb是一款非关系型数据库,而pair索引则是一种特殊的索引类型,用于确保集合中的文档对的唯一性。要创建唯一的pair索引,您需要使用Mongodb的createIndex方法,并指定索引的字段以及唯一性选项。通过正确设置索引,您可以有效地避免重复数据的插入,提高数据的一致性和准确性。接下来,让我们一起来看看具体的操作步骤吧!
问题内容
我正在使用 mongodb,我想在 2 个字段上使一对唯一。
以下是我到目前为止所做的:
func (repository *translationrepository) createindexes(collection *mongo.collection) error { models := []mongo.indexmodel{ { keys: bson.d{{"object_id", 1}, {"object_type", 1}}, options: options.index().setunique(true), }, { keys: bson.d{{"expire_at", 1}}, options: options.index().setexpireafterseconds(0), }, } opts := options.createindexes().setmaxtime(10 * time.second) _, err := collection.indexes().createmany(context.background(), models, opts) return err}
登录后复制
但是当我像这样插入 2 条记录时
{ "object_id" : "abc", "object_type": "sample" }{ "object_id" : "edf", "object_type": "sample" }
登录后复制
数据库中只有1条记录
{ "object_id" : "edf", "object_type": "sample" }
登录后复制
第二个已经覆盖了第一个
下面是我插入记录的示例代码
TranslationForm := entity.TranslationForm{ ObjectID: "ABC", ObjectType: "SAMPLE", SourceLanguage: "en", TargetLanguage: "cn", Content: "something", ExpireAt: time.Now(), }res, err := repository.collection.InsertOne(context.TODO(), TranslationForm)
登录后复制
解决方法
我应该管理你的场景。让我分享一个简单的程序来展示我所取得的成就。
package mainimport ( "context" "fmt" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options")type Object struct { ObjectId string `json:"object_id" bson:"object_id"` ObjectType string `json:"object_type" bson:"object_type"`}func main() { ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*10) defer cancelFunc() clientOptions := options.Client().ApplyURI("mongodb://root:root@localhost:27017") mongoClient, err := mongo.Connect(ctx, clientOptions) if err != nil { panic(err) } defer mongoClient.Disconnect(ctx) demoDb := mongoClient.Database("demodb") defer demoDb.Drop(ctx) myCollection := demoDb.Collection("myCollection") defer myCollection.Drop(ctx) // create index indexModel := mongo.IndexModel{ Keys: bson.D{ bson.E{ Key: "object_id", Value: 1, }, bson.E{ Key: "object_type", Value: 1, }, }, Options: options.Index().SetUnique(true), } idxName, err := myCollection.Indexes().CreateOne(ctx, indexModel) if err != nil { panic(err) } fmt.Println("index name:", idxName) // delete documents defer func() { if _, err := myCollection.DeleteMany(ctx, bson.M{}); err != nil { panic(err) } }() // insert first doc res, err := myCollection.InsertOne(ctx, Object{ObjectId: "abc", ObjectType: "SAMPLE"}) if err != nil { panic(err) } fmt.Println(res.InsertedID) // insert second doc // res, err = myCollection.InsertOne(ctx, Object{ObjectId: "abc", ObjectType: "SAMPLE"}) => ERROR res, err = myCollection.InsertOne(ctx, Object{ObjectId: "def", ObjectType: "SAMPLE"}) // => OK! if err != nil { panic(err) } fmt.Println(res.InsertedID) // list all docs var objects []Object cursor, err := myCollection.Find(ctx, bson.M{}) if err != nil { panic(err) } if err = cursor.All(ctx, &objects); err != nil { panic(err) } fmt.Println(objects)}
登录后复制
现在,我将回顾一下所有主要步骤:
object 结构的定义,这是您需要的简化版本。请注意实际使用的 bson 注释。为了这个演示,您可以安全地省略 json 。与 mongo 生态系统相关的设置:上下文创建(有超时)客户端设置(连接到通过 docker 运行的本地 mongodb 实例)创建名为 demodb 的数据库和名为 mycollection 的集合。另外,我在退出程序时推迟了删除这些内容的调用(只是为了清理)。在字段 object_id 和 object_type 上创建唯一复合索引。请注意 options 字段,该字段使用 setunique 方法声明索引的唯一性。添加文档。请注意,该程序不允许您插入两个具有相同字段的文档。您可以尝试评论/取消评论这些案例,以便再次确认。出于调试目的,我最终列出了集合中的文档,以检查第二个文档是否已添加。
我希望这个演示能够解答您的一些疑问。让我知道并谢谢!
以上就是如何为Mongodb创建唯一的pair索引?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2483985.html