如何為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) }
現在,我將回顧所有主要步驟:
-
object
結構的定義,這是您需要的簡化版本。請注意實際使用的bson
註解。為了這個演示,您可以安全地省略json
。 - 與 mongo 生態系相關的設定:
- 上下文建立(有超時)
- 客戶端設定(連接到透過 docker 運行的本機 mongodb 實例)
- 建立名為
demodb
的資料庫和名為mycollection
的集合。另外,我在退出程式時推遲了刪除這些內容的呼叫(只是為了清理)。
- 在欄位
object_id
和object_type
上建立唯一複合索引。請注意options
字段,該字段使用setunique
方法聲明索引的唯一性。 - 新增文件。請注意,該程式不允許您插入兩個具有相同欄位的文件。您可以嘗試評論/取消評論這些案例,以便再次確認。
- 出於調試目的,我最終列出了集合中的文檔,以檢查第二個文檔是否已新增。
我希望這個演示能夠解答您的一些疑問。讓我知道並謝謝!
以上是如何為Mongodb建立唯一的pair索引?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

C 更適合需要直接控制硬件資源和高性能優化的場景,而Golang更適合需要快速開發和高並發處理的場景。 1.C 的優勢在於其接近硬件的特性和高度的優化能力,適合遊戲開發等高性能需求。 2.Golang的優勢在於其簡潔的語法和天然的並發支持,適合高並發服務開發。
