Search⌘ K
AI Features

MongoDB: Insert

Explore how to insert data into MongoDB using Go by implementing the InsertOne method and creating a RESTful API endpoint. This lesson guides you through connecting to MongoDB, building query objects with the builder pattern, and integrating database insert operations into your server to handle user data effectively.

We'll cover the following...

Once we are able to connect to our database, it’s time to write some data to it. We will use the User type and assume all required types to be already present.

MongoDB insert one

To start with, let us write the method in our MongoDB package that will perform an insert into our database. We already know the signature for this function because it has to implement the DB interface.

Go (1.18.2)
func (mongodb *Mongo) Insert(query *db.Query) error {
collection := mongodb.Client.
Database(query.Database).
Collection(query.Collection)
context, cancel := context.WithTimeout(context.Background(), TIMEOUT)
defer cancel()
_, err := collection.InsertOne(context, query.Object)
return err
}

In lines 3 and 4, we specify the exact database and collection we want access to and store a pointer to this resource in ...