Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Go 驱动程序
/ /

替换文档

在本指南中,您可以学习;了解如何使用Go驾驶员对MongoDB集合中的文档执行替换操作。替换操作的执行方式与更新操作不同。更新操作仅修改目标文档中的指定字段。替换操作会删除目标文档中的所有字段,然后替换为新字段。

ReplaceOne() 需要替换文档,即您要替换现有文档的文档。 替换文档使用以下格式:

bson.D{{"<field>", "<value>"}, {"<field>", "<value>"}, ... }

ReplaceOne() 如果操作成功,则返回UpdateResult类型,其中包含有关替换操作的信息。 UpdateResult类型包含以下属性:

属性
说明

MatchedCount

过滤匹配的文档数

ModifiedCount

操作修改的文档数量

UpsertedCount

该操作更新或插入的文档数量

UpsertedID

更新或插入文档的 _id,如果没有则为 nil

如果多个文档与传递给 ReplaceOne() 的查询过滤器匹配,则该方法将选择并替换第一个匹配的文档。如果没有文档与查询筛选器匹配,则替换操作将失败。

以下文档描述了一种厨房用品:

{
"_id" : 2056,
"item" : "Mug",
"brand" : "Simply Ceramics",
"price" : 2.99,
"material" : "Glass"
}

下面的示例使用 ReplaceOne() 方法将此文档替换为另一个文档,其中包含一个值为 "Cup" 的 item 字段和一个值为 107 的 quantity 字段:

filter := bson.D{{"_id", 2056}}
replacement := bson.D{{"item", "Cup"}, {"quantity", 107}}
result, err := collection.ReplaceOne(context.TODO(), filter, replacement)
fmt.Printf("Documents matched: %v\n", result.MatchedCount)
fmt.Printf("Documents replaced: %v\n", result.ModifiedCount)
Documents matched: 1
Documents replaced: 1

被替换文档包含替换文档的内容和不可变的 _id 字段,具体如下:

{
"_id" : 2056,
"item" : "Cup",
"quantity" : 107
}

注意

设置示例

此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用 Atlas示例数据集包含的 sample_restaurants数据库中的 restaurants集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。

以下示例对 restaurants 集合执行以下操作:

  • 匹配 name 值为 "Rizzo's Fine Pizza" 的文档

  • 用新文档替换匹配的文档

// Replaces the first document that matches a filter by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
type Restaurant struct {
Name string
RestaurantId string `bson:"restaurant_id,omitempty"`
Cuisine string `bson:"cuisine,omitempty"`
Address interface{} `bson:"address,omitempty"`
Borough string `bson:"borough,omitempty"`
Grades []interface{} `bson:"grades,omitempty"`
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/zh-cn/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
filter := bson.D{{"name", "Rizzo's Fine Pizza"}}
// Creates a new document containing "Name" and "Cuisine" fields
replacement := Restaurant{Name: "Rizzo's Pizza", Cuisine: "Pizza/American"}
// Replaces the first document that matches the filter with a new document
result, err := coll.ReplaceOne(context.TODO(), filter, replacement)
if err != nil {
panic(err)
}
// Prints the number of modified documents
if result.MatchedCount != 0 {
fmt.Println("Number of documents replaced:", result.ModifiedCount)
}
// When you run this file for the first time, it should print:
// Number of documents replaced: 1
}
Number of documents replaced: 1

运行完整示例后,您可在 restaurants 集合中找到以下替换的文档:

{
"_id" : ObjectId("..."),
"name" : "Rizzo's Pizza",
"cuisine" : "Pizza/American"
}

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

Update Documents

在此页面上