我想使用 _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
}
关于mongodb - 如何更新文档数组中的多个嵌套字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61864861/