欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

记住,项目已解决 - mongodb

最编程 2024-10-18 09:20:35
...

insertOrUpdate

filter := bson.M{"_id": objectId}
update := bson.M{
    "$set": bson.M{
        "name": "Updated Name",
        "age":  30,
    },
}

opts := options.FindOneAndUpdate().
    SetUpsert(true).                 // 没有匹配文档时插入新文档
    SetReturnDocument(options.After) // 返回更新后的文档,不加这行,setUpsert不生效

result := collection.FindOneAndUpdate(context.TODO(), filter, update, opts)

if err := result.Decode(&updatedDocument); err != nil {
    log.Fatal(err)
}

fmt.Printf("Updated document: %+v\n", updatedDocument)

推荐阅读