Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created May 22, 2019 11:28
Show Gist options
  • Save joduplessis/7fd016461af71bc1af7a60a0dd15f370 to your computer and use it in GitHub Desktop.
Save joduplessis/7fd016461af71bc1af7a60a0dd15f370 to your computer and use it in GitHub Desktop.
Gets a document in a date range (30 days ago) using the new MongoDB drivers. Based off of Yack.app.
package main
import (
"fmt"
"time"
"log"
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Create a struct for the contact object
type Contact struct {
ID primitive.ObjectID `json:"_id" bson:"_id"`
Conditions []string `json:"conditions" bson:"conditions"`
Consultations []string `json:"consultations" bson:"consultations"`
Goals []string `json:"goals" bson:"goals"`
User primitive.ObjectID `json:"user" bson:"user"`
Contact primitive.ObjectID `json:"contact" bson:"contact"`
Confirmed bool `json:"confirmed" bson:"confirmed"`
UpdatedAt time.Time `bson:"updatedAt"`
CreatedAt time.Time `bson:"createdAt"`
}
func main() {
// Create a new contact to use Mongo with
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
// Create the Mongo client
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
// Connect to the DB
err = client.Connect(ctx)
// If there is an error, output it
if (err != nil) { log.Fatal(err) }
// Get the contacts collection
// Each contact will have a date & token asociated that we need
collection := client.Database("database_name").Collection("collection_name")
// Find all document in the collection
// It will return a cursor we can use for the results
day := time.Now().AddDate(0, -1, 0)
startOfDay := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, time.UTC).Format(time.RFC3339)
endOfDay := time.Date(day.Year(), day.Month(), day.Day(), 23, 59, 59, 99, time.UTC).Format(time.RFC3339)
cur, err := collection.Find(ctx, bson.M{"updatedAt": bson.M{"$gt": startOfDay, "$lt": endOfDay}})
// Again: if there are any errors
if err != nil { log.Fatal(err) }
// 'defer' will executes after this block finishes executing
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
contact := Contact{}
err := cur.Decode(&contact)
if err != nil { log.Fatal(err) }
// Get the resulting document
// raw := cur.Current
fmt.Println(contact)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment