Skip to content

Instantly share code, notes, and snippets.

@cesartalves
Created January 17, 2021 19:17
Show Gist options
  • Save cesartalves/7e717b7c511ea41d2cf6bca17c5990a4 to your computer and use it in GitHub Desktop.
Save cesartalves/7e717b7c511ea41d2cf6bca17c5990a4 to your computer and use it in GitHub Desktop.
Golang Mongo Search example
package main
import (
"context"
"fmt"
"log"
"time"
"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 price struct {
Cents int32
Currency_ISO string
}
type Product struct {
Id primitive.ObjectID `bson:"_id"`
Vehicle_Model string
Price price
}
func main() {
context, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(context, options.Client().ApplyURI("mongodb://localhost:27017"))
defer func() {
if err = client.Disconnect(context); err != nil {
panic(err)
}
}()
err = client.Connect(context)
collection := client.Database("autocommerce_development").Collection("products")
options := options.Find()
options.SetSort(bson.D{{"vehicle_model", -1}})
options.SetLimit(10)
filters := bson.M{
"price.cents": bson.M{"$gt": 20000.0 * 100},
"vehicle_model": bson.D{
{"$regex", primitive.Regex{Pattern: "Modelo"}},
},
}
cursor, err := collection.Find(context, filters, options)
defer cursor.Close(context)
if err != nil {
log.Fatal(err)
}
var results []Product
for cursor.Next(context) {
var result Product
err := cursor.Decode(&result)
if err != nil {
log.Fatal(err)
}
results = append(results, result)
}
if err := cursor.Err(); err != nil {
log.Fatal(err)
}
for _, product := range results {
//https: //golang.org/pkg/fmt/
fmt.Printf("%+v\n", product)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment