Table of Contents
Question content
Solution
Home Backend Development Golang How to create unique pair index for Mongodb?

How to create unique pair index for Mongodb?

Feb 10, 2024 pm 05:00 PM

How to create unique pair index for Mongodb?

php editor Xigua will introduce you how to create a unique pair index for Mongodb. Mongodb is a non-relational database, and the pair index is a special index type used to ensure the uniqueness of document pairs in the collection. To create a unique pair index, you need to use Mongodb's createIndex method and specify the fields of the index as well as the uniqueness option. By correctly setting indexes, you can effectively avoid the insertion of duplicate data and improve data consistency and accuracy. Next, let’s take a look at the specific steps!

Question content

I am using mongodb and I want to make a pair unique on 2 fields.

Here's what I've done so far:

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
}
Copy after login

But when I insert 2 records like this

{
    "object_id"  : "abc",
    "object_type": "sample" 
}

{
    "object_id"  : "edf",
    "object_type": "sample" 
}
Copy after login

There is only 1 record in the database

{
    "object_id"  : "edf",
    "object_type": "sample" 
}
Copy after login

The second one has overwritten the first one

The following is my sample code for inserting records

TranslationForm := entity.TranslationForm{
        ObjectID:       "ABC",
        ObjectType:     "SAMPLE",
        SourceLanguage: "en",
        TargetLanguage: "cn",
        Content:        "something",
        ExpireAt:       time.Now(),
    }
res, err := repository.collection.InsertOne(context.TODO(), TranslationForm)
Copy after login

Solution

I should manage your scenario. Let me share a simple program to show what I achieved.

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)
}
Copy after login

Now, I'll go over all the major steps:

  1. object Definition of the structure, this is a simplified version of what you need. Please note the actual use of bson comments. For the sake of this demonstration, you can safely omit json.
  2. Settings related to the mongo ecosystem:
    1. Context creation (with timeout)
    2. Client settings (connect to local mongodb instance running via docker)
    3. Create a database named demodb and a collection named mycollection. Also, I defer the call to delete these when exiting the program (just to clean up).
  3. Create a unique composite index on fields object_id and object_type. Note the options field, which declares the uniqueness of the index using the setunique method.
  4. Add documentation. Please note that the program does not allow you to insert two documents with the same fields. You can try commenting/uncommenting these cases to confirm again.
  5. For debugging purposes, I ended up listing the documents in the collection to check if the second document was added.

I hope this demo answers some of your questions. Let me know and thanks!

The above is the detailed content of How to create unique pair index for Mongodb?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Getting Started with Go: A Beginner's Guide Getting Started with Go: A Beginner's Guide Apr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. Python: The Pros and Cons Golang vs. Python: The Pros and Cons Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

See all articles