2

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

0

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.