Golang mongodb insert data | Go

 collection := client.Database("your_database").Collection("your_collection")
_, err := collection.InsertOne(ctx, bson.D{{"name", "John Doe"}, {"age", 30}})
if err != nil {
    log.Fatal(err)
}

fmt.Println("Data inserted successfully!") 

AI Explanation

This Go code snippet shows how to insert a document into a MongoDB collection using the official MongoDB driver for Go. 1. `client.Database("your_database").Collection("your_collection")` - This code retrieves a reference to a collection named "your_collection" in the database named "your_database" using the MongoDB client object. 2. `_, err := collection.InsertOne(ctx, bson.D{{"name", "John Doe"}, {"age", 30}})` - This line inserts a new document into the collection. The `InsertOne` method is used to insert a single document, and the document to be inserted is provided as a BSON Document. In this case, the document contains two fields: "name" with the value "John Doe" and "age" with the value 30. The function returns an error if the insertion fails. 3. `if err != nil { log.Fatal(err) }` - This block checks if there was an error during the insertion. If an error occurs, the program terminates and logs the error using `log.Fatal`. 4. `fmt.Println("Data inserted successfully!")` - If the document is successfully inserted, this line prints "Data inserted successfully!" to the console. Overall, this code snippet demonstrates a simple example of inserting a document into a MongoDB collection using the official MongoDB driver for Go.