php小編魚仔在本文中將向大家介紹如何在MongoDB的文件中更新陣列。 MongoDB是一種非關係型資料庫,它的文件結構非常靈活,可以包含各種類型的數據,包括陣列。在實際的開發中,我們經常需要對儲存在數組中的資料進行更新操作。本文將詳細說明如何使用MongoDB的更新運算子來更新文件中的數組,以及一些常見的使用情境和注意事項。無論你是剛接觸MongoDB還是已經有一定經驗的開發者,都能從本文中獲得有益的知識與實務經驗。
我正在嘗試更新 mongo 文件中的陣列項目。
event 是文檔,我透過事件 id 找到它,然後我需要透過識別任務名稱來識別任務數組中的哪個物件需要更改。
知道我哪裡出錯了
事件結構
type event struct { eventid string `json:"eventid" bson:"eventid"` eventowner string `json:"eventowner" bson:"eventowner"` eventtitle string `json:"eventtitle" bson:"eventtitle"` eventdatetime string `json:"eventdatetime" bson:"eventdatetime"` eventlocation eventaddress `json:"eventlocation" bson:"eventlocation"` eventtotalticket int `json:"eventtotalticket" bson:"eventtotalticket"` eventavailableticket int `json:"eventavailableticket" bson:"eventavailableticket"` eventcoverimage string `json:"eventcoverimage" bson:"eventcoverimage"` eventdescription string `json:"eventdescription" bson:"eventdescription"` lat string `json:"lat" bson:"lat"` long string `json:"long" bson:"long"` task []task `json:"task" bson:"task"` }
任務結構:
type task struct { tasktitle string `json:"tasktitle" bson:"tasktitle"` initalbudget float32 `json:"initialbudget" bson:"initialbudget"` supplier string `json:"suppid" bson:"suppid"` agreedprice float32 `json:"agreedprice" bson:"agreedprice"` iscomplete bool `json:"iscomplete" bson:"iscomplete"` }
這就是我想做的
func (e *EventServiceImpl) UpdateTask(eventid *string, task *models.Task) error { //filter := bson.D{bson.E{Key: "eventid", Value: eventid}, bson.E{Key: "tasktitle", Value: task.TaskTitle}} filter := bson.M{"$and": []bson.M{{"eventid": eventid}, {"task": bson.E{Key: "tasktitle", Value: task.TaskTitle}}}} update := bson.D{bson.E{Key: "$set", Value: bson.D{bson.E{Key: "task", Value: bson.M{"tasktitle": task.TaskTitle, "initialbudget": task.InitalBudget, "suppid": task.Supplier, "agreedprice": task.AgreedPrice, "iscomplete": task.IsComplete}}}}} result, _ := e.eventcollection.UpdateOne(e.ctx, filter, update) if result.MatchedCount != 1 { return errors.New("No matched document found to update") } return nil }
我總是收到「找不到要更新的符合文件」
這是解決方案
func (e *EventServiceImpl) UpdateTask(eventid *string, task *models.Task) error { filter := bson.M{"eventid": eventid, "task": bson.M{"$elemMatch": bson.M{"tasktitle": task.TaskTitle}}} update := bson.M{"$set": bson.M{"task.$.initialbudget": task.InitalBudget, "task.$.suppid": task.Supplier, "task.$.agreedprice": task.AgreedPrice, "task.$.iscomplete": task.IsComplete}} result, err := e.eventcollection.UpdateOne(e.ctx, filter, update) if err != nil { return err } if result.MatchedCount != 1 { return errors.New("No matched document found to update") } return nil }
以上是更新 mongdbo 文件中的數組的詳細內容。更多資訊請關注PHP中文網其他相關文章!