MongoDB: Insert
Learn how to insert a new document into MongoDB.
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.
Press + to interact
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 ...