Skip to content

Instantly share code, notes, and snippets.

@mwmahlberg
Created October 19, 2019 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwmahlberg/c46ec3ad3ccee028f0666ff7d5d8d98b to your computer and use it in GitHub Desktop.
Save mwmahlberg/c46ec3ad3ccee028f0666ff7d5d8d98b to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Driver struct {
Verified bool `json:"verified,omitempty"`
License string
}
type Student struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
IsDriver bool `json:"isdriver,omitempty"`
Driver Driver `json:"driver,omitempty" bson:"driver,Inline"`
}
var studentCollection *mongo.Collection
func GetAllDrivers() []Driver {
// Options
projections := bson.D{
{"driver", 1},
/* {"driver.verified", 1},
{"driver.license", 1}, */
}
// Filter for search
filter := bson.M{"isdriver": true}
cur, err := studentCollection.Find(context.TODO(), filter, options.Find().SetProjection(projections))
// Error while finding documents
if err != nil {
fmt.Println(err)
return []Driver{}
}
var drivers []Driver
var student Student
// Get the next result from the cursor
for cur.Next(context.TODO()) {
err := cur.Decode(&student)
if err != nil {
fmt.Println(err)
}
drivers = append(drivers, student.Driver)
}
if err := cur.Err(); err != nil {
fmt.Println(err)
}
cur.Close(context.TODO())
return drivers
}
func main() {
// My connection, do not bother
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
studentCollection = client.Database("test").Collection("drivers")
d := GetAllDrivers()
fmt.Printf("%#v", d)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment