檢查物件數組中的值是否存在 golang
php小編百草在本文將為您介紹如何在golang中檢查物件陣列中的值是否存在。在開發過程中,我們經常需要對陣列進行操作和判斷,而在某些情況下,我們需要檢查某個值是否存在於一個物件陣列中。這個過程可能會涉及遍歷數組、比較值等操作,以下我們將一步步為您介紹如何實現這個功能。
問題內容
我試圖在向 mongo 資料庫附加新值之前檢查該值是否存在,但每次都會收到錯誤。
obid, _ := primitive.objectidfromhex(id) query := bson.d{{key: "_id", value: obid}} var result bson.m er := r.collection.findone(ctx, bson.m{"_id": obid, "statusdata.status": bson.m{"$in": []string{string(p.status)}}}).decode(&result) if er != nil { if er == mongo.errnodocuments { return nil, errors.new(fmt.sprintf("err na %v, %v", er.error(), p.status)) } return nil, errors.new(fmt.sprintf("err norr %v", er.error())) } doc, err := utils.todoc(p) if err != nil { return nil, errors.new(err.error()) } update := bson.d{{key: "$set", value: doc}} res := r.collection.findoneandupdate(ctx, query, update, options.findoneandupdate().setreturndocument(1))
我的文件看起來像這樣
{ "statusdata": [ { "status": "new", "message": "you created a new dispatch request", "createdat": "1657337212751", "updatedat": null }, { "status": "assigned", "message": "justin has been assigned to you", "createdat": "1657412029130", "updatedat": null, "_id": "62ca19bdf7d864001cabfa4a" } ], "createdat": "2022-07-10t00:09:01.785z",
.... }
有不同的狀態,我想確保在使用新值更新資料庫之前不會多次將相同的狀態傳送到資料庫。
type statustype string const ( new statustype = "new" acknowledged statustype = "acknowledged" assigned statustype = "assigned" reject statustype = "rejected" cancel statustype = "cancelled" complete statustype = "completed" )
utils.todoc
func todoc(v interface{}) (doc *bson.d, err error) { data, err := bson.marshal(v) if err != nil { return } err = bson.unmarshal(data, &doc) return }
嘗試更新
filter := bson.m{ "_id": obid, "statusdata.status": bson.m{"$ne": p.status}, } update := bson.m{ "$push": bson.m{ "statusdata": newstatustoadd, }, "$set": bson.d{{key: "$set", value: doc}}, } result, err := r.collection.updateone(ctx, filter, update) if err != nil { // handle error return nil, errors.new(err.error()) } if result.matchedcount == 0 { // the status already exists in statusdata } else if result.modifiedcount == 1 { // new status was added successfuly }
回傳錯誤
"write exception: write errors: [The dollar ($) prefixed field '$set' in '$set' is not allowed in the context of an update's replacement document. Consider using an aggregation pipeline with $replaceWith.]"
解決方法
使用篩選器來排除具有您要新增的狀態的文件。如果狀態已存在於陣列中,則此篩選器將不符合任何文件。僅當狀態尚未新增時才會執行更新操作:
var newStatusToAdd = ... // This is the new statusData document you want to add filter := bson.M{ "_id": obId, "statusData.status": bson.M{"$ne": p.Status}, } update := bson.M{ "$push": bson.M{ "statusData": newStatusToAdd, }, "$set": doc, } result, err := r.collection.UpdateOne(ctx, filter, update) if err != nil { // Handle error return } if result.MatchedCount == 0 { // The status already exists in statusData } else if result.ModifiedCount == 1 { // new status was added successfuly }
以上是檢查物件數組中的值是否存在 golang的詳細內容。更多資訊請關注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的優勢在於其簡潔的語法和天然的並發支持,適合高並發服務開發。
