How can I update multiple nested fields in an array of documents

Viewed 2234

I want to update one of the documents CLIENTDATA USING _id and clientID as the filter keys how can I update it and is their any method through aggregation. How can I update swapnil name to something else using id and clientID as my filters

//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
}

Here is the image of my MongoDB database with the above collection.

enter image description here

1 Answers

You need to use positional operator to update element in an array, so instead of using clientData.name you should use 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
}
Related