我想更新数据库中的一些字段,也想它返回一些字段,你能建议如何检索返回字段吗?

所以我在这里使用,

returnFields := map[string]interface{}{"order_id":1}  
 
data := FindAndUpdateVerticalsOffers(updateQuery, updateFields, returnFields) 

如何从“data”获取order_id:

 
func FindAndUpdateVerticalsOffers(updateQuery map[string]interface{}, updateFields interface{}, returnFields map[string]interface{}) map[string]interface{} { 
 
    session := db.GetSession() 
    defer session.Close() 
    collection := session.DB("").C(VerticalsOffersName) 
    updateSet := bson.M{"$set": updateFields} 
    return collection.FindOneAndUpdate(updateQuery, updateSet, returnFields) 
} 

请您参考如下方法:

I want to update some fields in DB and also want to it to return some fields,

如果您使用 mongo-go-driver (当前为 v1.1),您可以利用 FindOneAndUpdate()它找到一个文档并更新它,返回原始文档或更新后的文档。

该方法接受 FindOneAndUpdateOptions 的参数, 它支持 projection .例如:

collection := client.Database("dbName").Collection("collName") 
 
// Sets projection (or return fields) 
findUpdateOptions := options.FindOneAndUpdateOptions{} 
findUpdateOptions.SetProjection(bson.M{"order_id": 1}) 
 
result := collection.FindOneAndUpdate(context.TODO(),  
                                      bson.M{"foo":1},  
                                      bson.M{"$set": bson.M{"bar":1}},  
                                      &findUpdateOptions) 
 
doc := bson.M{} 
err = result.Decode(&doc) 

上面的查询会匹配字段foo为1的文档,更新字段bar为1,结果只返回order_id .请注意,默认情况下还会返回 _id 字段。你可以suppress the _id field通过将其设置为 0 来避免投影。

请注意 FindOneAndUpdate 的返回类型是 SingleResult对象,表示从操作返回的单个文档。如果操作返回错误,则 SingleResult 的 Err 方法将返回该错误。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!