首页 > 后端开发 > Golang > 正文

如何为Mongodb创建唯一的pair索引?

PHPz
发布: 2024-02-10 17:00:10
转载
1073 人浏览过

如何为Mongodb创建唯一的pair索引?

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 main

import (
    "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)
}
登录后复制

现在,我将回顾一下所有主要步骤:

  1. object 结构的定义,这是您需要的简化版本。请注意实际使用的 bson 注释。为了这个演示,您可以安全地省略 json
  2. 与 mongo 生态系统相关的设置:
    1. 上下文创建(有超时)
    2. 客户端设置(连接到通过 docker 运行的本地 mongodb 实例)
    3. 创建名为 demodb 的数据库和名为 mycollection 的集合。另外,我在退出程序时推迟了删除这些内容的调用(只是为了清理)。
  3. 在字段 object_idobject_type 上创建唯一复合索引。请注意 options 字段,该字段使用 setunique 方法声明索引的唯一性。
  4. 添加文档。请注意,该程序不允许您插入两个具有相同字段的文档。您可以尝试评论/取消评论这些案例,以便再次确认。
  5. 出于调试目的,我最终列出了集合中的文档,以检查第二个文档是否已添加。

我希望这个演示能够解答您的一些疑问。让我知道并谢谢!

以上是如何为Mongodb创建唯一的pair索引?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!