Overview
En esta guía, puede aprender cómo insertar documentos en una colección MongoDB.
Para poder buscar, actualizar y eliminar documentos en MongoDB, debe insertarlos. Puede insertar un documento usando el InsertOne()
método, o inserte varios documentos utilizando el método InsertMany() o BulkWrite().
Las siguientes secciones se centran en InsertOne() y InsertMany(). Para aprender a usar el método BulkWrite(), consulte
Guía deoperaciones masivas.
El campo _id
En MongoDB, cada documento debe contener un campo _id único.
Las dos opciones para gestionar este campo son:
Gestione usted mismo este campo, asegurándose de que cada valor que utilice sea único.
Permitir que el controlador genere automáticamente valores
ObjectIdúnicos. El controlador genera valoresObjectIdúnicos para los documentos en los que no se especifica explícitamente un_id.
A menos que proporcione garantías sólidas de unicidad, MongoDB recomienda que deje que el controlador genere automáticamente valores _id.
Nota
Los valores duplicados _id violan las restricciones de índice único, lo que hace que el controlador devuelva un WriteError.
Para obtener más información sobre el campo _id, consulte la entrada del Manual del servidor en
Unique Indexes.
Para aprender más sobre la estructura y las reglas de los documentos, consultar la entrada del Manual del Servidor sobre Documentos.
Insertar un documento
Utilice el método InsertOne() para insertar un solo documento en una colección.
Tras una inserción exitosa, el método devuelve una instancia InsertOneResult que contiene el _id del nuevo documento.
Ejemplo
Este ejemplo utiliza la siguiente estructura Book como modelo para los documentos de la colección books:
type Book struct { Title string Author string }
El siguiente ejemplo crea e inserta un documento en la colección books utilizando el método InsertOne():
coll := client.Database("db").Collection("books") doc := Book{Title: "Atonement", Author: "Ian McEwan"} result, err := coll.InsertOne(context.TODO(), doc) fmt.Printf("Inserted document with _id: %v\n", result.InsertedID)
Inserted document with _id: ObjectID("...")
Modificar el comportamiento de InsertOne()
Puedes modificar el comportamiento de InsertOne() construyendo y pasando una estructura InsertOneOptions opcional. Las opciones disponibles para configurar con InsertOneOptions son:
Opción | Descripción |
|---|---|
| If true, allows the write to opt-out of document level validation.Default: false |
Construya un InsertOneOptions de la siguiente manera:
opts := options.InsertOne().SetBypassDocumentValidation(true)
Insertar un documento Ejemplo: Archivo completo
Nota
Configuración de ejemplo
Este ejemplo se conecta a una instancia de MongoDB mediante una URI de conexión. Para obtener más información sobre cómo conectarse a su instancia de MongoDB, consulte la guía "Crear un MongoClient". Este ejemplo también utiliza la restaurants colección de la sample_restaurants base de datos incluida en los conjuntos de datos de ejemplo de Atlas. Puede cargarlos en su base de datos en la versión gratuita de MongoDB Atlas siguiendo la Guía de introducción a Atlas.
El siguiente ejemplo inserta un nuevo documento en la colección restaurants. Seleccione el Struct o pestaña bson.D para ver el código correspondiente:
El siguiente código utiliza una estructura para insertar un nuevo documento en la colección restaurants:
// Inserts a single document describing a restaurant by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Defines the structure of a restaurant document type Restaurant struct { Name string RestaurantId string `bson:"restaurant_id,omitempty"` Cuisine string `bson:"cuisine,omitempty"` Address any `bson:"address,omitempty"` Borough string `bson:"borough,omitempty"` Grades []any `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/es/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) } }() // Inserts a sample document describing a restaurant into the collection coll := client.Database("sample_restaurants").Collection("restaurants") newRestaurant := Restaurant{Name: "8282", Cuisine: "Korean"} result, err := coll.InsertOne(context.TODO(), newRestaurant) if err != nil { panic(err) } // Prints the ID of the inserted document fmt.Printf("Document inserted with ID: %s\n", result.InsertedID) // When you run this file for the first time, it should print output similar // to the following: // Document inserted with ID: ObjectID("...") }
Document inserted with ID: ObjectID("...")
El siguiente código utiliza un tipo bson.D para insertar un nuevo documento en la colección restaurants:
// Inserts a single document describing a restaurant by using the Go driver with bson.D 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" ) 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/es/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) } }() // Inserts a sample document describing a restaurant into the collection using bson.D coll := client.Database("sample_restaurants").Collection("restaurants") newRestaurant := bson.D{ bson.E{Key: "name", Value: "8282"}, bson.E{Key: "cuisine", Value: "Korean"}, } result, err := coll.InsertOne(context.TODO(), newRestaurant) if err != nil { panic(err) } // Prints the ID of the inserted document fmt.Printf("Document inserted with ID: %s\n", result.InsertedID) // When you run this file for the first time, it should print output similar // to the following: // Document inserted with ID: ObjectID("...") }
Document inserted with ID: ObjectID("...")
Inserta varios documentos
Utilice el método InsertMany() para insertar varios documentos en una colección.
Tras una inserción exitosa, el método InsertMany() devuelve una instancia InsertManyResult que contiene los campos _id de los documentos insertados.
Ejemplo
El siguiente ejemplo crea e inserta varios documentos en la colección books utilizando el método InsertMany():
coll := client.Database("myDB").Collection("favorite_books") docs := []any{ Book{Title: "Cat's Cradle", Author: "Kurt Vonnegut Jr."}, Book{Title: "In Memory of Memory", Author: "Maria Stepanova"}, Book{Title: "Pride and Prejudice", Author: "Jane Austen"}, } result, err := coll.InsertMany(context.TODO(), docs) fmt.Printf("Documents inserted: %v\n", len(result.InsertedIDs)) for _, id := range result.InsertedIDs { fmt.Printf("Inserted document with _id: %v\n", id) }
Después de ejecutar el código anterior, el resultado será similar al siguiente:
Documents inserted: 3 Inserted document with _id: ObjectID("...") Inserted document with _id: ObjectID("...") Inserted document with _id: ObjectID("...")
Modificar el comportamiento de InsertMany()
Puedes modificar el comportamiento de InsertMany() construyendo y pasando una estructura InsertManyOptions opcional. Las opciones disponibles para configurar con InsertManyOptions son:
Opción | Descripción |
|---|---|
| If true, allows the write to opt-out of document level validation.Default: false |
| If true, the driver sends documents to the server in the order provided.
If an error occurs, the driver and server end all remaining insert operations.
To learn more, see Ordered Behavior.Default: false |
Construya un InsertManyOptions de la siguiente manera:
opts := options.InsertMany().SetBypassDocumentValidation(true).SetOrdered(false)
Comportamiento ordenado
Suponga que desea insertar los siguientes documentos:
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 1, "title": "Blueberries for Sal" } { "_id": 3, "title": "Goodnight Moon" }
Si intenta insertar estos documentos con el valor predeterminado InsertManyOptions, aparece un BulkWriteException en el tercer documento debido al valor _id repetido, pero los documentos anteriores al documento que produce el error aún se insertan en su colección.
Nota
Puede obtener un reconocimiento de inserción exitosa del documento incluso si ocurre una BulkWriteException:
type Book struct { ID int `bson:"_id"` Title string } ... docs := []any{ Book{ID: 1, Title: "Where the Wild Things Are"}, Book{ID: 2, Title: "The Very Hungry Caterpillar"}, Book{ID: 1, Title: "Blueberries for Sal"}, Book{ID: 3, Title: "Goodnight Moon"}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { fmt.Printf("A bulk write error occurred, but %v documents were still inserted.\n", len(result.InsertedIDs)) } for _, id := range result.InsertedIDs { fmt.Printf("Inserted document with _id: %v\n", id) }
A bulk write error occurred, but 2 documents were still inserted. Inserted document with _id: 1 Inserted document with _id: 2
Después de ejecutar el código anterior, su colección contendrá los siguientes documentos:
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" }
Insertar muchos ejemplos: archivo completo
Nota
Configuración de ejemplo
Este ejemplo se conecta a una instancia de MongoDB mediante una URI de conexión. Para obtener más información sobre cómo conectarse a su instancia de MongoDB, consulte la guía "Crear un MongoClient". Este ejemplo también utiliza la restaurants colección de la sample_restaurants base de datos incluida en los conjuntos de datos de ejemplo de Atlas. Puede cargarlos en su base de datos en la versión gratuita de MongoDB Atlas siguiendo la Guía de introducción a Atlas.
El siguiente ejemplo inserta varios documentos nuevos en la colección restaurants. Seleccione la pestaña Struct o bson.D para ver el código correspondiente:
El siguiente código utiliza una estructura para insertar varios documentos nuevos en la colección restaurants:
// Inserts sample documents describing restaurants by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Defines the structure of a restaurant document type Restaurant struct { Name string RestaurantId string `bson:"restaurant_id,omitempty"` Cuisine string `bson:"cuisine,omitempty"` Address any `bson:"address,omitempty"` Borough string `bson:"borough,omitempty"` Grades []any `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/es/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") // Creates two sample documents describing restaurants newRestaurants := []any{ Restaurant{Name: "Rule of Thirds", Cuisine: "Japanese"}, Restaurant{Name: "Madame Vo", Cuisine: "Vietnamese"}, } // Inserts sample documents into the collection result, err := coll.InsertMany(context.TODO(), newRestaurants) if err != nil { panic(err) } // Prints the IDs of the inserted documents fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs)) for _, id := range result.InsertedIDs { fmt.Printf("\t%s\n", id) } // When you run this file for the first time, it should print output similar // to the following: // 2 documents inserted with IDs: // ObjectID("...") // ObjectID("...") }
2 documents inserted with IDs: ObjectID("...") ObjectID("...")
El siguiente código utiliza un tipo bson.D para insertar varios documentos nuevos en la colección restaurants:
// Inserts sample documents describing restaurants by using the Go driver with bson.D 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" ) 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/es/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") // Creates two sample documents describing restaurants using bson.D newRestaurants := []interface{}{ bson.D{ bson.E{Key: "name", Value: "Rule of Thirds"}, bson.E{Key: "cuisine", Value: "Japanese"}, }, bson.D{ bson.E{Key: "name", Value: "Madame Vo"}, bson.E{Key: "cuisine", Value: "Vietnamese"}, }, } // Inserts sample documents into the collection result, err := coll.InsertMany(context.TODO(), newRestaurants) if err != nil { panic(err) } // Prints the IDs of the inserted documents fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs)) for _, id := range result.InsertedIDs { fmt.Printf("\t%s\n", id) } // When you run this file for the first time, it should print output similar // to the following: // 2 documents inserted with IDs: // ObjectID("...") // ObjectID("...") }
2 documents inserted with IDs: ObjectID("...") ObjectID("...")
Información Adicional
Para obtener más información sobre cómo realizar las operaciones mencionadas, consulte las siguientes guías:
Documentación de la API
Para obtener más información sobre cualquiera de los métodos o tipos discutidos en esta guía, consultar la siguiente documentación de la API: