搜索
首页后端开发Golang如何为Mongodb创建唯一的pair索引?

如何为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。如有侵权,请联系admin@php.cn删除
与GO接口键入断言和类型开关与GO接口键入断言和类型开关May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和错误。使用errors.is和错误。May 02, 2025 am 12:11 AM

Go语言的错误处理通过errors.Is和errors.As函数变得更加灵活和可读。1.errors.Is用于检查错误是否与指定错误相同,适用于错误链的处理。2.errors.As不仅能检查错误类型,还能将错误转换为具体类型,方便提取错误信息。使用这些函数可以简化错误处理逻辑,但需注意错误链的正确传递和避免过度依赖以防代码复杂化。

在GO中进行性能调整:优化您的应用程序在GO中进行性能调整:优化您的应用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

GO的未来:趋势和发展GO的未来:趋势和发展May 02, 2025 am 12:01 AM

go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿制药,云 - 纳蒂维德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

了解Goroutines:深入研究GO的并发了解Goroutines:深入研究GO的并发May 01, 2025 am 12:18 AM

goroutinesarefunctionsormethodsthatruncurranceingo,启用效率和灯威量。1)shememanagedbodo'sruntimemultimusingmultiplexing,允许千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

了解GO中的初始功能:目的和用法了解GO中的初始功能:目的和用法May 01, 2025 am 12:16 AM

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

了解GO界面:综合指南了解GO界面:综合指南May 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

从恐慌中恢复:何时以及如何使用recover()从恐慌中恢复:何时以及如何使用recover()May 01, 2025 am 12:04 AM

在Go中使用recover()函数可以从panic中恢复。具体方法是:1)在defer函数中使用recover()捕获panic,避免程序崩溃;2)记录详细的错误信息以便调试;3)根据具体情况决定是否恢复程序执行;4)谨慎使用,以免影响性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器