登录
首页 >  Golang >  Go问答

更新嵌套字段 | 修改文档数组

来源:stackoverflow

时间:2024-03-24 23:00:37 433浏览 收藏

本文介绍了如何使用嵌套字段更新 MongoDB 文档。具体来说,它探讨了使用 positional operator 更新文档数组中特定元素的方案。通过使用 positional operator,可以更新数组中匹配指定过滤条件的元素,而无需使用其索引。文中提供了更新函数的代码示例,说明如何使用 positional operator 更新数组中的元素。

问题内容

我想使用 _id 和 clientid 作为过滤器键更新文档 clientdata 之一,我如何更新它以及它们通过聚合的任何方法。如何使用 id 和 clientid 作为过滤器将 swapnil 名称更新为其他名称

//UpdateClient is used to update clientData
func UpdateClient(Data structure.ClientDataUpdate) bool {
    connection := GetConnection()
    if connection == nil {
        return false
    }
    collection := connection.Database("IAGENT").Collection("CLIENTDATA")
    filter := bson.M{"$and": []interface{}{bson.M{"_id": Data.ID}, bson.M{"clientData.clientID": Data.ClientID}}}
    update := bson.M{"$set": bson.M{"clientData.name": Data.Name, "clientData.policy": Data.Policy, "clientData.expiryDate": Data.ExpiryDate,"clientData.metaData":Data.Metadata,"clientData.mobile":Data.Phone}}
    _, err := collection.UpdateOne(context.TODO(), filter, update)
    if err != nil {
        fmt.Println("updating the Data", err)
        return false
    }
    return true
}

这是我的 mongodb 数据库的图像,其中包含上述集合。


解决方案


您需要使用 positional operator 来更新数组中的元素,因此不应使用 clientdata.name,而应使用 clientdata.$.name

//UpdateClient is used to update clientData
func UpdateClient(Data structure.ClientDataUpdate) bool {
    connection := GetConnection()
    if connection == nil {
        return false
    }
    collection := connection.Database("IAGENT").Collection("CLIENTDATA")
    filter := bson.M{"$and": []interface{}{bson.M{"_id": Data.ID}, bson.M{"clientData.clientID": Data.ClientID}}}
    update := bson.M{"$set": bson.M{"clientData.$.name": Data.Name, "clientData.$.policy": Data.Policy, "clientData.$.expiryDate": Data.ExpiryDate,"clientData.$.metaData":Data.Metadata,"clientData.$.mobile":Data.Phone}}
    _, err := collection.UpdateOne(context.TODO(), filter, update)
    if err != nil {
        fmt.Println("updating the Data", err)
        return false
    }
    return true
}

本篇关于《更新嵌套字段 | 修改文档数组》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>