Convert Figma logo to code with AI

mongodb logomongo-go-driver

The Official Golang driver for MongoDB

8,135
892
8,135
14

Top Related Projects

1,972

The MongoDB driver for Go

1,302

Qmgo - The Go driver for MongoDB. It‘s based on official mongo-go-driver but easier to use like Mgo.

3,670

SQL-first Golang ORM

16,124

general purpose extensions to golang's database/sql

36,742

The fantastic ORM library for Golang, aims to be developer friendly

Quick Overview

The mongodb/mongo-go-driver is the official MongoDB driver for the Go programming language. It provides a high-performance, idiomatic Go interface to MongoDB, allowing developers to easily interact with MongoDB databases in their Go applications.

Pros

  • Native Go implementation for optimal performance
  • Comprehensive support for MongoDB features and operations
  • Well-documented and actively maintained by MongoDB
  • Supports both synchronous and asynchronous operations

Cons

  • Steeper learning curve compared to simpler ORM-like libraries
  • Requires more boilerplate code for basic operations
  • May be overkill for simple applications with basic database needs
  • Documentation can be overwhelming for beginners

Code Examples

  1. Connecting to MongoDB:
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    log.Fatal(err)
}
defer client.Disconnect(context.TODO())
  1. Inserting a document:
collection := client.Database("testdb").Collection("users")
doc := bson.D{{"name", "John Doe"}, {"age", 30}}
result, err := collection.InsertOne(context.TODO(), doc)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Inserted document with ID: %v\n", result.InsertedID)
  1. Querying documents:
filter := bson.D{{"age", bson.D{{"$gt", 25}}}}
cursor, err := collection.Find(context.TODO(), filter)
if err != nil {
    log.Fatal(err)
}
defer cursor.Close(context.TODO())

for cursor.Next(context.TODO()) {
    var result bson.M
    err := cursor.Decode(&result)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Found document: %v\n", result)
}

Getting Started

  1. Install the driver:

    go get go.mongodb.org/mongo-driver/mongo
    
  2. Import the required packages:

    import (
        "context"
        "go.mongodb.org/mongo-driver/mongo"
        "go.mongodb.org/mongo-driver/mongo/options"
        "go.mongodb.org/mongo-driver/bson"
    )
    
  3. Connect to MongoDB and perform operations (see code examples above for usage).

Competitor Comparisons

1,972

The MongoDB driver for Go

Pros of mgo

  • Simpler API and easier to use for beginners
  • Lightweight and has fewer dependencies
  • Better performance in some scenarios, especially for read operations

Cons of mgo

  • No longer actively maintained (last commit in 2018)
  • Lacks support for newer MongoDB features and improvements
  • May have compatibility issues with newer MongoDB versions

Code Comparison

mgo:

session, err := mgo.Dial("mongodb://localhost")
if err != nil {
    log.Fatal(err)
}
defer session.Close()

collection := session.DB("test").C("documents")
err = collection.Insert(bson.M{"name": "John", "age": 30})

mongo-go-driver:

client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost"))
if err != nil {
    log.Fatal(err)
}
defer client.Disconnect(context.TODO())

collection := client.Database("test").Collection("documents")
_, err = collection.InsertOne(context.TODO(), bson.M{"name": "John", "age": 30})

The mongo-go-driver provides a more modern and actively maintained solution with support for the latest MongoDB features. It offers better compatibility with newer MongoDB versions and follows a more idiomatic Go approach. However, it may have a steeper learning curve and slightly more verbose code compared to mgo.

mgo, while simpler to use, lacks ongoing support and may not be suitable for projects requiring the latest MongoDB features or long-term maintenance.

1,302

Qmgo - The Go driver for MongoDB. It‘s based on official mongo-go-driver but easier to use like Mgo.

Pros of qmgo

  • Simpler API with a more intuitive interface for common MongoDB operations
  • Built-in support for hooks (before/after insert, update, etc.)
  • Automatic index creation based on struct tags

Cons of qmgo

  • Less comprehensive feature set compared to the official driver
  • Smaller community and potentially less frequent updates
  • May not support some advanced MongoDB features or edge cases

Code Comparison

mongo-go-driver:

client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
collection := client.Database("test").Collection("users")
result, _ := collection.InsertOne(context.TODO(), bson.D{{"name", "John"}, {"age", 30}})

qmgo:

cli, _ := qmgo.NewClient(context.Background(), &qmgo.Config{Uri: "mongodb://localhost:27017"})
db := cli.Database("test")
coll := db.Collection("users")
_, _ = coll.InsertOne(context.Background(), bson.M{"name": "John", "age": 30})

The qmgo code is slightly more concise and follows a more intuitive structure for database and collection access. However, both libraries offer similar functionality for basic operations. The choice between them depends on specific project requirements and developer preferences.

3,670

SQL-first Golang ORM

Pros of Bun

  • Supports multiple databases (PostgreSQL, MySQL, SQLite) vs. MongoDB-only
  • Offers a more SQL-like query syntax, familiar to SQL developers
  • Provides built-in query logging and performance monitoring

Cons of Bun

  • Less mature and smaller community compared to Mongo Go Driver
  • Limited to relational databases, not suitable for document-based NoSQL needs
  • May have fewer advanced features specific to MongoDB operations

Code Comparison

Bun query example:

db.NewSelect().
    Model((*User)(nil)).
    Where("id = ?", 1).
    Scan(ctx)

Mongo Go Driver query example:

collection.FindOne(ctx, bson.M{"_id": 1}).
    Decode(&user)

Summary

Bun is a versatile ORM for relational databases with a SQL-like syntax, while Mongo Go Driver is specifically designed for MongoDB. Bun offers multi-database support and built-in monitoring, but has a smaller community. Mongo Go Driver provides deeper MongoDB-specific features and a larger ecosystem. The choice depends on your database requirements and preference for query syntax.

16,124

general purpose extensions to golang's database/sql

Pros of sqlx

  • Simpler API for working with SQL databases, reducing boilerplate code
  • Supports multiple SQL databases (MySQL, PostgreSQL, SQLite) with a unified interface
  • Lightweight and easy to integrate into existing projects

Cons of sqlx

  • Limited to SQL databases, not suitable for NoSQL solutions like MongoDB
  • Lacks some advanced features and optimizations specific to MongoDB

Code Comparison

sqlx:

db, _ := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
rows, _ := db.Queryx("SELECT * FROM users WHERE id = $1", 1)
var user User
for rows.Next() {
    rows.StructScan(&user)
}

mongo-go-driver:

client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
collection := client.Database("testdb").Collection("users")
var user User
err := collection.FindOne(context.TODO(), bson.M{"id": 1}).Decode(&user)

Summary

sqlx is a lightweight extension to Go's database/sql package, offering a simpler API for working with SQL databases. It supports multiple SQL databases and is easy to integrate into existing projects. However, it's limited to SQL databases and lacks some MongoDB-specific features.

mongo-go-driver, on the other hand, is specifically designed for MongoDB, providing optimized performance and full support for MongoDB's features. It offers a more complex API but allows for greater flexibility when working with NoSQL data structures.

Choose sqlx for SQL database projects with simpler requirements, and mongo-go-driver for MongoDB-based applications or when advanced NoSQL features are needed.

36,742

The fantastic ORM library for Golang, aims to be developer friendly

Pros of GORM

  • Supports multiple databases (MySQL, PostgreSQL, SQLite, SQL Server) vs. MongoDB-specific driver
  • Provides a higher-level ORM abstraction with features like hooks, associations, and migrations
  • More extensive documentation and larger community support

Cons of GORM

  • May have slightly lower performance due to ORM overhead compared to direct driver usage
  • Less flexibility for complex queries or MongoDB-specific features
  • Steeper learning curve for developers new to ORM concepts

Code Comparison

GORM example:

db.Where("name = ?", "jinzhu").First(&user)
db.Create(&User{Name: "John", Age: 30})

mongo-go-driver example:

filter := bson.D{{"name", "jinzhu"}}
collection.FindOne(ctx, filter).Decode(&user)
collection.InsertOne(ctx, bson.D{{"name", "John"}, {"age", 30}})

Summary

GORM is a versatile ORM for multiple SQL databases, offering high-level abstractions and extensive features. The mongo-go-driver is a specialized MongoDB driver, providing direct access to MongoDB-specific functionality. Choose GORM for SQL databases and broader ORM features, or mongo-go-driver for MongoDB-specific projects requiring low-level control and optimal performance.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

docs docs

MongoDB Go Driver

The MongoDB supported driver for Go.

See the following resources to learn more about upgrading from version 1.x to 2.0.:

Requirements

  • Go 1.18 or higher. We aim to support the latest versions of Go.
  • Go 1.22 or higher is required to run the driver test suite.
  • MongoDB 3.6 and higher.

Installation

The recommended way to get started using the MongoDB Go driver is by using Go modules to install the dependency in your project. This can be done either by importing packages from go.mongodb.org/mongo-driver and having the build step install the dependency or by explicitly running

go get go.mongodb.org/mongo-driver/v2/mongo

When using a version of Go that does not support modules, the driver can be installed using dep by running

dep ensure -add "go.mongodb.org/mongo-driver/v2/mongo"

Usage

To get started with the driver, import the mongo package and create a mongo.Client with the Connect function:

import (
    "context"
    "time"

    "go.mongodb.org/mongo-driver/v2/mongo"
    "go.mongodb.org/mongo-driver/v2/mongo/options"
    "go.mongodb.org/mongo-driver/v2/mongo/readpref"
)

client, _ := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017"))

Make sure to defer a call to Disconnect after instantiating your client:

defer func() {
    if err = client.Disconnect(ctx); err != nil {
        panic(err)
    }
}()

For more advanced configuration and authentication, see the documentation for mongo.Connect.

Calling Connect does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to, use the Ping method:

ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

_ = client.Ping(ctx, readpref.Primary())

To insert a document into a collection, first retrieve a Database and then Collection instance from the Client:

collection := client.Database("testing").Collection("numbers")

The Collection instance can then be used to insert documents:

ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

res, _ := collection.InsertOne(ctx, bson.D{{"name", "pi"}, {"value", 3.14159}})
id := res.InsertedID

To use bson.D, you will need to add "go.mongodb.org/mongo-driver/v2/bson" to your imports.

Your import statement should now look like this:

import (
    "context"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/v2/bson"
    "go.mongodb.org/mongo-driver/v2/mongo"
    "go.mongodb.org/mongo-driver/v2/mongo/options"
    "go.mongodb.org/mongo-driver/v2/mongo/readpref"
)

Several query methods return a cursor, which can be used like this:

ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

cur, err := collection.Find(ctx, bson.D{})
if err != nil {
  log.Fatal(err)
}

defer cur.Close(ctx)
for cur.Next(ctx) {
    var result bson.D
    if err := cur.Decode(&result); err != nil {
      log.Fatal(err)
    }

    // do something with result....
}

if err := cur.Err(); err != nil {
    log.Fatal(err)
}

For methods that return a single item, a SingleResult instance is returned:

var result struct {
    Value float64
}

filter := bson.D{{"name", "pi"}}
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

err = collection.FindOne(ctx, filter).Decode(&result)
if errors.Is(err, mongo.ErrNoDocuments) {
    // Do something when no record was found
} else if err != nil {
    log.Fatal(err)
}

// Do something with result...

Additional examples and documentation can be found under the examples directory and on the MongoDB Documentation website.

Network Compression

Network compression will reduce bandwidth requirements between MongoDB and the application.

The Go Driver supports the following compression algorithms:

  1. Snappy (snappy): available in MongoDB 3.4 and later.
  2. Zlib (zlib): available in MongoDB 3.6 and later.
  3. Zstandard (zstd): available in MongoDB 4.2 and later.

Specify Compression Algorithms

Compression can be enabled using the compressors parameter on the connection string or by using ClientOptions.SetCompressors:

opts := options.Client().ApplyURI("mongodb://localhost:27017/?compressors=snappy,zlib,zstd")
client, _ := mongo.Connect(opts)
opts := options.Client().SetCompressors([]string{"snappy", "zlib", "zstd"})
client, _ := mongo.Connect(opts)

If compressors are set, the Go Driver negotiates with the server to select the first common compressor. For server configuration and defaults, refer to networkMessageCompressors.

Messages compress when both parties enable network compression; otherwise, messages remain uncompressed

Feedback

For help with the driver, please post in the MongoDB Community Forums.

New features and bugs can be reported on jira: https://jira.mongodb.org/browse/GODRIVER

Contribution

Check out the project page for tickets that need completing. See our contribution guidelines for details.

Continuous Integration

Commits to master are run automatically on evergreen.

Frequently Encountered Issues

See our common issues documentation for troubleshooting frequently encountered issues.

Thanks and Acknowledgement

License

The MongoDB Go Driver is licensed under the Apache License.