首頁  >  文章  >  後端開發  >  如何為Mongodb建立唯一的pair索引?

如何為Mongodb建立唯一的pair索引?

PHPz
PHPz轉載
2024-02-10 17:00:101073瀏覽

如何為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刪除